Bundle and Minify CSS/JavaScript in MVC 4

In development, we like to use multiple JS and CSS files for modularity, readability and maintainability of code and it’s a good practice too. But in some cases it leads to degradation of the overall performance of the website. Because multiple JS and CSS files require multiple HTTP requests from a browser leads to degrade the performance & load time of your web pages.

Most of the current major browsers limit the number of simultaneous connections per each hostname to six. That means that while six requests are being processed, additional requests for assets on a host will be queued by the browser.

ASP.NET MVC 4 provides bundling and minification of CSS and JavaScript, which reduces the number of HTTP Requests and payload size resulting in faster and better performing ASP.NET MVC Websites. Bundling is a new feature in ASP.NET 4.5 that makes it easy to combine or bundle multiple files into a single file. You can create CSS, JavaScript and other bundles. Fewer files means fewer HTTP requests and that can improve first page load performance.

Minification is the practice of removing unnecessary characters from code to reduce its size, removing unnecessary spacing, and optimizing the CSS code; thus improving load times. When Javascript and CSS are compressed all comments are usually removed, as well as unneeded “white space” characters like space, new line, and tab. Additionally code can be further formatted onto a single line instead of multiple. In the case of CSS, this improves load time performance because the size of the file downloaded is often significantly, significantly reduced. The bundling and minification framework provides a mechanism to process intermediate languages such as LESS, and apply transforms such as minification to the resulting bundle.

In ASP.NET MVC 4 – Microsoft provides System.Web.Optimization for Bundling and Minification, which is installed by default with new ASP.NET MVC4 application template as NuGet package. It allows the application to minify and bundle the files on the fly.
For bundling css and Js, you can use StyleBundle/ScriptBundle which is just syntaxtic sugar for not having to pass in new Css/JsMinify. See example below.

16-12-2013-1

But LESS transformation to the bundle has to be specified during the bundle creation. Bundle Transformer – a modular extension for System.Web.Optimization (also known as the Microsoft ASP.NET Web Optimization Framework). Classes CssTransformer and JsTransformer, included in the core of Bundle Transformer, implement interface IBundleTransform. They are intended to replace the standard classes CssMinify and JsMinify. See example below.

16-12-2013-2

16-12-2013-3

This entry was posted in Information Technology, MVC and tagged , , , , , , . Bookmark the permalink.