Bundling and Minification in ASP.NET 4.5


In this blog, we will look into two new features of ASP.NET 4.5 called as Bundling and Minification.  We can download Visual Studio 11 Developer Preview from http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=27543 to run ASP.NET 4.5 applications.  Bundling is a feature that will combine all your JavaScript and CSS files into a single file. Doing this, will reduce number of web requests to those individual files in turn improving website performance. Let’s say, if you have 20 JavaScript and 10 CSS files in your website. Without Bundling, we need to make 20 requests to individual JS files and 10 requests to CSS files. Using Bundling, we will make only two requests to get all those JS and CSS files. Minification is another built-in feature that will reduce the size of your JS & CSS files by removing whitespace and other characters that are not required. Both these features are integrated into ASP.NET and available for all kind of ASP.NET web applications like MVC, Web Pages etc.

Let’s have a feel of it, create a sample web application in VS 11 targeting to ASP.NET 4.5 as shown below:

Then, add multiple CSS files to your solution as shown below:

Let’s say, you are referencing all JS & CSS files in your master file for using in content pages as shown below:

 We will run fiddler 2 [network monitoring tool]/ IE Developer Tools to see the traffic after running the web application.

Now, we will add Bundling to our application by replacing the below code:

With

 

Add below entry in Global.asax [include System.Web.Optimization] on Application_start event to enable default bundling [it means bundle files under Scripts & Styles folder]:

BundleTable.Bundles.EnableDefaultBundles();

Run the application and Fiddler, we can see number of requests reduced:

JS & CSS files will be sorted alphabetically and merged into individual files with minification.

We can write custom bundling by defining the list of JS & CSS files to be bundled in Global.asax on Application_start as shown below: 

void Application_Start(object sender, EventArgs e) 
{
// Code that runs on application startup
//BundleTable.Bundles.EnableDefaultBundles();
Bundle b = new Bundle("~/CustomStyles1", typeof(CssMinify));
b.AddDirectory("~/Newstyles", "*.css",false);
b.AddFile("~/NewStyles1/ab.css");
BundleTable.Bundles.Add(b);
}

Add below entry to master file to load that bundle:

<link href="CustomStyles1" rel="stylesheet" type="text/css" />

By using Bundling and Minification, we can reduce size and number of requests to load our JS & CSS files of the website.

Note:This blog is based on features of preview only, and is subject to change in later releases.

Skip to main content