Search code examples
c#asp.net-mvcbundling-and-minification

Bundling all the Scripts and css of the project together


I have many scripts and css that I wrote in my MVC project.

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:

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.


Solution

  • 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. Therefore using many small bundles makes your page load slower. Maximum concurrent connections to the same domain for browsers