简体   繁体   English

将项目的所有脚本和CSS捆绑在一起

[英]Bundling all the Scripts and css of the project together

I have many scripts and css that I wrote in my MVC project. 我在MVC项目中编写了许多脚本和CSS。

I'm using Bundling and Minification and I know I can bundle them all togther like this: 我正在使用捆绑和缩小,我知道可以将它们全部捆绑在一起,如下所示:

bundles.Add(new StyleBundle("~/Content/site/").Include("~/Content/site/*.css"));
bundles.Add(new ScriptBundle("~/bundles/site").Include("~/Scripts/site/*.js"));

The problem is that I don't want to Render all the scripts and css together, I need one or two in each View, I know that I can manually register each script/css and then I will be able to render them separately in each View: 问题是我不想一起Render所有脚本和css,在每个视图中都需要一个或两个,我知道我可以手动注册每个脚本/ css,然后可以在每个视图中分别render它们视图:

bundles.Add(new ScriptBundle("~/bundles/script1").Include("~/Scripts/site/script1.js"));
bundles.Add(new ScriptBundle("~/bundles/script2").Include("~/Scripts/site/script2.js"));

And then in one View: 然后在一个视图中:

@section scripts{
    @Scripts.Render("~/bundles/script1")
}

And in the second one: 在第二个中:

@section scripts{
    @Scripts.Render("~/bundles/script2")
}

My question is if this is correct or there is a better solution for that. 我的问题是这是否正确,或者有更好的解决方案。

Yes, it is correct to build multiple bundles that are tailored to the Views. 是的,构建针对视图定制的多个捆绑包是正确的。

Note that you can add multiple specific scripts/styles to a bundle: 请注意,您可以将多个特定的脚本/样式添加到包中:

var commonJsBundle = new ScriptBundle("~/bundles/Common/Js");
commonJsBundle.Include("~/Scripts/jquery-{version}.js");
commonJsBundle.Include("~/Scripts/jquery-ui-{version}.js");

@Scripts.Render("~/bundles/Common/Js")

So you do not need to have a bundle for each individual script, rather bundle all custom scripts for a page (or Area) together. 因此,您不必为每个单独的脚本都捆绑在一起,而是将页面(或区域)的所有自定义脚本捆绑在一起。

PS: as noted by Stefan, there is a tradeoff between bundle size and the number of parallel connections a browser supports when downloading them. PS:正如Stefan所指出的,在捆绑包大小和浏览器下载时支持的并行连接数量之间需要权衡。 Therefore using many small bundles makes your page load slower. 因此,使用许多小捆绑包会使页面加载速度变慢。 Maximum concurrent connections to the same domain for browsers 浏览器到同一域的最大并发连接数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM