How to do CSS and JavaScript Bundling and Minification in ASP.NET
October 31, 2013 by Anuraj
.Net .Net 4.0 ASP.Net Javascript
ASP.NET 4.5 includes a new feature to minify and bundle CSS and JavaScript within your web application. Static content like javascript and css files contains lot of white spaces and comments. Bundling and minification improves load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript.) In the past, the recommended technique was enabling compression either using programmatically or you can configure it in IIS. But it was difficult configure and has got some performance issues.
Here is a sample web application, which contains 6 style sheets and 3 javascript files, and this is network traffic before css and javascript bundling and minification.
And here is the same web application after enabling css and javascript bundling and minification.
You can enable bundling and minification using Microsoft Web Optimization framework. You can install it using nuget.
Install-Package Microsoft.AspNet.Web.Optimization
Once you install the nuget package, you can write following code in global.asax file, in the Application_Start event.
You can refer the javascript and css file in the _layout.cshtml / *.master file like this
Instead of selecting all the files in the scripts / styles folder, you can also specify / order of the files like this.
Bundling and minification is enabled or disabled by setting the value of the debug attribute in the compilation Element in the Web.config file.
You can override the Web.config setting with the EnableOptimizations property on the BundleTable class.
Happy Programming
Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub