MVC4 to MVC3 #1: Bundling and Minification

If your web hosting company provides web servers that support only MVC3 (cough, godaddy), and you are dying to use bundling and minification, well here is a solution. This is a simple addition that will make your website work a bit faster. Bundling is the process of joining a number of files into a single one, for example the browser can get the site's css in a single request whilst using the download slots that would have been used to download multiple css files for something else. Minification is the process of removing whitespace and comments in order to make the bundled files smaller. Minification works with css and javascript files, and in the latter case it also shortens the variable names. The result is a bit unreadable to the human eye, but the smaller file size makes for quicker page loading.

So here is how to do it:

First you need to get the required library files that were added to MVC4, which are System.Web.Optimization.dll and WebGrease.dll. If you aren't sure where you might find them, start a new MVC4 solution and copy the files from the generated bin folder to the MVC3 project's own bin folder.

Next, create a folder named App_Start and inside it create a new class named BundleConfig.cs. The skeleton for this new class is as follows:

using System.Web.Optimization;

namespace same_as_your_main_project
public classBundleConfig
public static void RegisterBundles(BundleCollection bundles)


Inside the RegisterBundles method, we will then add the necessary bundle information.

bundles.Add(new StyleBundle("~/Content/css").Include(

In the above example, I have added 3 css files named style, reset and 960.css and bundled them in a virtual file named ~/Content/css, which is how we will refer to them on the web page itself. Javascript files are bundled in a similar way, simply by replacing StyleBundle with ScriptBundle.

Now these bundles need to be initialised every time that the application is started. To do this, open the Global.asax.cs file and add this line somewhere in the Application_Start() method:


The last thing to do is to add a link for the virtual bundle inside the page. Easy, just add this line of code:

‹link rel="stylesheet" type="text/css" href= "@BundleTable.Bundles.ResolveBundleUrl("~/Content/css")" /›

Note that the name inside the parameter that we are passing (shown in bold) is the same as the one we added earlier, which is what makes the link work. Hurrah, we have a working bundling and minification solution on MVC3. The neat thing is that the generated file will also instruct the browser to cache it for one year, resulting in additional speed gains for repeated visits!

Buy me a coffee Buy me a coffee


Add your comments