ASP.NET MVC – Is It Good Practice to Have One Bundle Per View?

asp.net-mvcbundlingminify

Since bundling and minification is all about optimization and making pages load faster, it appears to me that it would be logical to create one bundle for scripts and one bundle for styles per view basis, so that to load all scripts and styles a browser will need to make 2 requests at most. So let's say I have a _Layout.cshtml where I need 3 js files bootstrap.js,jquery.js and some custom1.js I can create one bundle, something like this:

bundles.Add(new ScriptBundle("~/bundles/layout").Include(
          "~/Scripts/bootstrap.js",
          "~/Scripts/jquery.js",
          "~/Scripts/custom1.js"));

Then let's say I have another view User.cshtml where I need bootstrap.js,jquery.js and custom2.js, again I create one bundle:

bundles.Add(new ScriptBundle("~/bundles/user").Include(
          "~/Scripts/bootstrap.js",
          "~/Scripts/jquery.js",
          "~/Scripts/custom2.js"));

Same approach can be used for style bundles.
But from what I see it's not a common practice to do it this way usually bundles are created on the type basis, e.g., one for bootstrap, one for jquery, one for custom js/css files etc. But wouldn't doing so increase the loading time of the page, because having more bundles means more request to the server. Also what is the problem of doing things the way I described at the beginning?

Best Answer

I think it might almost even be counterproductive to use a single bundle per page.

There's an overhead for creation of the bundle... albeit, that overhead is incurred once per application instance (it's cached by the application after the first call), but if you have a new bundle for each page, that means for each distinct page you visit, a new bundle has to be created before it can be served. That would defeat the purpose of the bundles considerably, I think.

Rather, I usually have two bundles: one core bundle which every page is expected to require and will hardly ever change once the initial project is set up. This includes core styles, jQuery/knockout, other base-vendor libraries.

The second bundle is usually per-application context (e.g., the Users bundle might have modular stuff related to users in general, but not necessarily to a specific page).

Anything page-specific doesn't usually even go into a bundle.

The practical performance effect of bundling (at least for business applications that I tend to write) isn't really all that great, considering that once the client has called it the first time, it's there until it changes again anyway.

If you have a public site where you expect a greater number of first-time visitors, you might take a slightly different approach.