Search code examples
c#asp.net-mvcasp.net-mvc-4bundlesasp.net-optimization

When to use bundles in MVC4


In MVC 4 I can use @Styles.Render("~/Content/css") to called a bundle of CSS files defined BundleConfig file instead of calling the CSS directly.

When should we use bundle instead of calling directly the file? I understand it clearly when we have various CSS files to simplify the code. But if there is a single CSS file, should we use a bundle or call it directly?


Solution

  • Combining multiple files is only one of the various interesting features of bundling.

    For instance, bundles allow you to apply various transformations (e.g. LESS for CSS; Minification; Obfuscation for JS; etc).

    Another nice feature is its built in caching mechanism. This ensures that clients will only retrieve a specific version of your bundle once. Any change to your bundle will be picked up by the client on the next request.

    Bundles can also be used for run-time swapping of CSS or JS files. For instance, serving debug version of a JS framework on your development environment, while serving a minified version on your production environment. The switch can be made in your Global.asax.cs using any custom logic you like (e.g. Web.config parameter; compiler conditionals; etc)