Bundling and Minification are two tools available since  ASP.NET 4 that will make your application load faster as they reduce the number of files to be downloaded (bundling) as well as removing all white spaces / comments and shortening the variable names (when possible) so that file sizes get smaller.

This is specially important as when a page is loaded most browsers will limit the amount of resources that are retrieved down to 6 (so it retrieves maximum 6 files simultaneously) so by reducing the number of files to be downloaded we can guarantee a faster load time (and we all love that, don’t we?)

Let’s see what a page load looks like in chrome when no bundling or minification occurs:

bundling and minification ASP.NET MVC

As expected chrome will only download a maximum of 6 resources at the time  and anything else is put into a queue and it will be downloaded once one of the 6 files is completed. in the above example we can see how some .js files had to wait for previous files to be finished downloading.

And to make it worse, as the number of files grow in your application this will cost your visitors valuable time waiting for all files to be downloaded (even worse they may not even come back!).

How can I speed up my website load?

One of the first steps to optimize your website is to set up bundling and minification, fortunately this is really easy in .NET.

Before we continue there are a couple of files that will have to be modified, as follow:

  • Web.config: this is the file where most of the configuration is done for a web site/application
  • Bundle.config: Found in the App_Start folder (web applications)

The first thing you’ll need to do is enable bundle and minification, this can be done by setting the value of the compilation element to true in your web.config file

Alternatively you can specify the Bundle.EnableOptimizations property to true inside the Bundle.Config file (which takes precedence over web.config file):

Once bundling and minification has been set up we now need to tell the ASP.NET framework which files we want bundled and minified, very similar to the above code but now adding the to-be bundled/minified files:

The above will bundle the specified 12 files into one and will minimize it was well (awesome !)

Lastly we’ll need to add a reference to it on the page (master page / layout) where we want those scripts to be rendered:

Now let’s run the application and open up the developer tools (F12) to check out the new bundles:

bundling and minification enabled ASP.NET MVC

Neat !, now we have it bundled, one a closer inspection (clicking on the bundled file) we can see what a minified file looks like:

ASP.NET minified javascript file

It is important to note that you would only want to do this on your production site, as you don’t want to debug your code on a minified file, ewww