In Summary
When bundling and minifying JavaScript, is it good practice to have a single site-wide JS bundle or multiple specific bundles?
If the latter, then how can these bundles be added to each View (not layout) and still get the server to return the individual non-minified JS files when in debug mode?
In Detail
I read a very interesting article detailing how to use the bundling and minification that is available in the MVC4 framework in the an ASP.NET MVC3 web application: click for article
In this article, it describes how to add a link to a particular bundle from the layout page:
Scripts.Render("~/bundles/MyBundle")
And I can see how this approach is great for creating a site-wide bundle.
However, I’m not sure what the best-practice is regarding whether to have a single site-wide bundle, or multiple specialized bundles and I’d appreciate advice here. As I see it, the pros and cons of a single site-wide bundle are:
- Cons:
- slows down initial load of home page (even with minimization)
- may be harder to ensure no JS conflicts.
- Pros:
- all subsequent pages have nothing new to download
- just one bundle to administer
Okay – assuming that best practice turns out to be multiple bundles…. That being the case, I see how easy it is to add a bundle to a layout page, but how about specific views? Each View should register the JS that it requires (in a script section) and then this is added to the bottom of the page’s body so that it loads last (unlike CSS which you add to the Header so that it loads first). I managed this using the following code, but the problem with this route is that the JS always comes out as the single minified file which isn’t that helpful in debug mode.
@<script src="@Scripts.Url("~/bundles/myBundle")"></script>
Many thanks in advance
Griff
You can do both. In order to render the specialized bundles, you can do this:
Create a scripts section in your _Layout.cshtml. I usually put mine at the bottom of the page just before the closing body tag, but you could also put it in the head:
Then, in your view, you define the section like so:
When you do it this way, the bundle will only be compressed and minified when you either compile with debug=”false” or explicitly set
BundleTable.EnableOptimizations = trueduring debug time.