Sunday, November 25, 2012

Bundling and Minification

Bundling and minification was introduced with ASP.net 4.5, which makes to improve the performance of the application. So this feature is useful in the production time than in the development time.
  • Bundling reduces the number of individual HTTP requests to the server. For example by combining multiple CSS files or JavaScript files into one single CSS file or JavaScript file.
  • Minification reduces the file download size of CSS or JavaScript by removing white spaces, comments, variable lengths and other unnecessary characters.
Create an ASP.net MVC project. In this post we'll consider about the JavaScript bundling. For that copy the jquery-1.7.1.js file in the Scripts folder and paste that file three times and rename those. For example dilanA.js,  dilanB.js and dilanC.js.
Add a new controller called DemoController and add the default action and the view. In the view add references for the above three JavaScript files.
Run the project and go to the Index page of the DefaultController. Using Google Chrome observe the network usage.
There are three requests for each JavaScript file and lot of time has consumed for each request. Now we have to bundle and minify the above three JavaScript files.
Bundling and minification is enabled or disabled by setting the value of debug attribute in the Web.config file.
To enable that, set the debug value to false.
You can override Web.config setting with the EnableOptimizations property on the BundleTable class. Add following code in the BundleConfig.cs file in the App-Start folder.
Add the following code into the RegisterBundles method in the BundleConfig.cs file.
Also in the default view of the DemoController, add the following code.
Now browse again the default view of the DemoController and check the network usage. Only one single request for all the three JavaScript files. And lesser time than previous request. Also the size of the requested file has minified, if we compare that to the total size of the all the three files.
Also we can use async attribute in HTML 5 for these bundling and minification. For that make the DOCTYPE tag in to HTML 5 standard. After that add the bundling and minification code like below.

No comments:

Post a Comment