ASP NET Bundling

ASP NET Bundling is a great way to optimze the process of loading javascript and css files into your web application’s browser. It works by reducing the number of requests a browser needs to make in order to get all the javascript and css files required by the application. Instead of the browser making one request per file, it now only has to issue one request per bundle. Fewer requests by the browser means a faster loading page.

When you create a project in visual studio, it automatically enables bundling by adding the System.Web.Optimization Nuget package and creating a class named BundleConfig in the App_Start folder. This class has a method named RegisterBundles that allows you to define bundles by creating ScriptBundle objects and adding them to a BundleCollection. The ScriptBundle object has a contructor that takes the name of the bundle and an Include function that defines the path to the file that is being added to the bundle. Here is an example:

  bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js"));

This name of the bundle is significant because it will replace the include statement for the indivdual files. For example, the bundle created will be included in the project throught the Script.Render function defined in the System.Web.Optimization namespace. Here is the syntax:

  @Scripts.Render("~/bundles/jquery")

When you view your website in a browser, you will see just one script tag for your bundle which can be indentified by name, followed by a version stamped URL.

  <script src="/bundles/jquery?v=FVs3ACwOLIVInrAl5sdzR2jrCDmVOWFbZMY6g6Q0ulE1"></script>

For debugging, you can set the  BundleTable.EnableOptimizations boolean to false. This will allow you to see all the actual file names included in the bundle to troubleshoot any issues in debugging.