MVC ScriptBundle自定义排序。
今天发现MVC的ScriptBundle @Scripts.Render()后是按照我也不知道顺序显示在页面上的,后果就是jquery.min.js被排在了后面(反正我下面那堆默认jquery.min.js在第三个)导致javascript报错,所以很多情况不能自动按照首字母排序。
解决方法如下:
先新建一个类:
internal class AsIsBundleOrderer : IBundleOrderer { public virtual IEnumerable<BundleFile> OrderFiles(BundleContext context, IEnumerable<BundleFile> files) { return files; } }
之后绑定的时候这样绑定:
ScriptBundle mandatoryJs = new ScriptBundle("~/Metronic/mandatoryJs"); mandatoryJs.Orderer = new AsIsBundleOrderer(); mandatoryJs.Include( "~/plugins/Metronic/global/plugins/jquery.min.js", "~/plugins/Metronic/global/plugins/jquery-migrate.min.js", "~/plugins/Metronic/global/plugins/jquery-ui/jquery-ui.min.js", "~/plugins/Metronic/global/plugins/bootstrap/js/bootstrap.min.js", "~/plugins/Metronic/global/plugins/bootstrap-hover-dropdown/bootstrap-hover-dropdown.min.js", "~/plugins/Metronic/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js", "~/plugins/Metronic/global/plugins/jquery.blockui.min.js", "~/plugins/Metronic/global/plugins/jquery.cokie.min.js", "~/plugins/Metronic/global/plugins/uniform/jquery.uniform.min.js", "~/plugins/Metronic/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" ); bundles.Add(mandatoryJs);
就好了。
最后还可以再简化下:
bundles.Add(new ScriptBundle("~/Metronic/mandatoryJs") { Orderer = new AsIsBundleOrderer() }.Include( "~/plugins/Metronic/global/plugins/jquery.min.js", "~/plugins/Metronic/global/plugins/jquery-migrate.min.js", "~/plugins/Metronic/global/plugins/jquery-ui/jquery-ui.min.js", "~/plugins/Metronic/global/plugins/bootstrap/js/bootstrap.min.js", "~/plugins/Metronic/global/plugins/bootstrap-hover-dropdown/bootstrap-hover-dropdown.min.js", "~/plugins/Metronic/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js", "~/plugins/Metronic/global/plugins/jquery.blockui.min.js", "~/plugins/Metronic/global/plugins/jquery.cokie.min.js", "~/plugins/Metronic/global/plugins/uniform/jquery.uniform.min.js", "~/plugins/Metronic/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" ));
看起来就和一开始比较像了。