Look at Bundling in ASP.Net MVC 3

In this article, we will look into bundling and how to use it in a MVC 3 application. Bundling is a new feature introduced in ASP.NET 4.5 that can combine all your JavaScript and CSS files into a single file. Doing this will reduce the number of web requests to those individual files and in turn improve the website's performance. Let's say, if you have 20 JavaScript and 10 CSS files in your website. Without bundling, we need to make 20 requests for each individual JS files and 10 requests for each CSS file. Using bundling, we will make only two requests to load all those JS and CSS files. There will be a limit on the number of simultaneous connections/requests made by a browser to a single server at a time, for Internet Explorer 8 it's 6. Bundling will improve the website's performance by reducing the requests.

Let's explore the feature with a sample application. Create a sample MVC 3 application in Visual Studio 2010 and name it BundlingSample. Add a reference to the required JS and CSS files in "_layout.cshtml" as shown below:

Creating a MVC 3 application

Run the application, it will take 35 requests to load the page in IE 9 Developer tools:

IE9 Developer tools

Here, it's making a separate request to load each JS and CSS file. Let's add the bundling feature to the application.

Go to Solution Explorer, click "Manage NuGet Packages" and look for "Microsoft.AspNet.Web.Optimization" as shown below:

Optimization in Manage NuGet Packages

This will add the necessary assemblies (System.Web.Optimization.dll and WebGrease.dll) and settings in the web.config file.

Go to Global.asax.cs and add the following code to register the JS and CSS bundles on application start:

Global File

Replace the references to the JS and CSS files in "master page [_Layout.cshtml]" as shown below:

master page in MVC3

Here "~/scripts/jquery" is a virtual path that does not need to exist. Run the application, we can see the number of requests is reduced to load the page.

Run the application

We can use Bundling in Web Forms as well. For more details on implementing it in ASP.NET 4.5, refer to:

Bundling and Minification in ASP.NET 4.5

Similar Articles