Setting up the project
To show how bundles word, I create a new empty ASP.NET MVC project with the MVC folders. Then I install the following NuGet packages:
Analyzing the network load
You can analyze the network load with every browser by pressing the F12 key. This opens the dev tools which shows some useful information for development and debugging. Switch to the Network tab and disable Caching. Then reload the website. This lists all files requested and also displays a summary of the number of files transferred and the number of bytes.
As you can see there were quite some files transferred for such a simple page. In total nine requests were sent and 649 KB of data. This is a lot of data for such a simple page and could be a problem when the page grows and hosts more content. The solution for too many requests and too many sent data is bundling.
What is Bundling?
Setting up Bundles
The first step to use Bundles is installing the Microsoft.AspNet.Web.Optimization packages from NuGet. Then add the BundleConfig class to the App_Start folder. You don’t have to do this if you use the MVC template when creating a new project. Then Visual Studio automatically creates the class and installs the NuGet package for you.
If one file depends on the other one, make sure to add them in the right order. For example jQuery.validate needs jQuery, therefore the jQuery file needs to be added first.
Using Bundles in ASP.NET MVC
After creating the Bundles, I have to add the RegisterBundle method in the Global.asx file to make sure it is called at the start of the application. To register the RegisterBunle method in the Global.asx file add the following line of code: BundleConfig.RegisterBundles(BundleTable.Bundles);
The next step is to add the System.Web.Optimization namespace to the web.config viel in the Views folder.
Then set the value of the debug attribute in the compilation tag in the web.config to false. If this is set to true, the browser requests all the files with separate requests and doesn’t use bundling.
In theory, fewer files get requested and the transferred data size is smaller too now. To test this I start the application and open the DevTools again. Then I reload the page.
As you can see only 3 requests and only 272 KB were sent. The request was finished after 53 ms instead of 127 ms without bundling.
You can find the source code on GitHub.