In this section you’re going to apply bundling and minification to our Surf Store application. Some great features included in the release of Visual Studio 2012 will boost and improve your page speed. You’re going to focus on the bundling and minification features that can be found under the
System.Web.Optimization namespace.
This namespace allows you to bundle and minify all of the JavaScript and CSS in the project folder sim- ply by sending a URL request to a preset virtual folder path. This code will work in both ASP.NET Web Forms and ASP.NET MVC, and is included automatically when you create a project in Visual Studio 2012. As you can see in figure 5.2, it can be found in the Solu- tion Explorer under the App_Start folder.
Figure 5.2 The default BundleConfig.cs is added to an ASP.NET 4.5 application
NOTE It should be noted that if you choose an empty ASP.NETMVC project tem- plate, you won’t find this class in your project. It is the simplest type of ASP.NET project and it doesn’t contain the full set of classes that you might need.
This BundleConfig class contains code that allows you to create Script and Style bun- dles that will bundle and minify the files. You’re going to run through an example in both ASP.NETMVC and Web Forms, but first it’s important to understand how each request is handled by ASP.NET.
In order to create a Script bundle, you’ll need to instantiate it by referencing a vir- tual path to the files that you want to bundle. The following listing contains code that you’ll need to implement or replace in the RegisterBundles() method of the BundleConfig class.
public static void RegisterBundles(BundleCollection bundles) {
bundles.Add(new StyleBundle("~/Styles/Css").Include(
"~/Content/Css/bootstrap.css",
"~/Content/Css/bootstrap-responsive.css"
));
bundles.Add(new ScriptBundle("~/Scripts/Js").Include(
"~/Scripts/bootstrap-alert.js", "~/Scripts/jquery-1.7.2.js"
));
}
The first virtual path referenced in the ScriptBundle is a reference to a file that doesn’t exist and can therefore be anything. In this case, I have pointed it to “~/
Styles/Css”. The code will then service any requests to the path provided. For exam- ple, if we want to apply this to CSS, we request:
<link href="/Styles/Css" rel="stylesheet">
As the website compiles and runs for the first time, ASP.NET will search the directory shown in the previous listing, and it will bundle and minify all the CSS files it finds.
When the virtual directory for the bundle is requested, it will send back a single HTTP response with all of the CSS combined and minified together. The same piece of code can be applied to all JavaScript files in a directory by simply changing the path to:
<script src="/Scripts/Js" type="text/javascript"></script>
By referencing the files, ASP.NET 4.5 will generate a reference to the bundled and mini- fied CSS and JavaScript files in the respective directories. For example, instead of seeing two CSS file references in the HTML, we now see only one combined file to give us only one HTTP request. Figure 5.3 shows the data that is inside the newly combined file.
The code in figure 5.3 has been word wrapped and cut short to make it easier to read, but you can see there are no spaces and the code is pretty difficult to read. Visual
Listing 5.5 Creating Script and Style bundles
A Style bundle that minifies and bundles two CSS files
A Script bundle that minifies and bundles two JavaScript files
65 New bundling and minifying features in ASP.NET 4.5
Studio has taken care of the hard work for us, and it only took a matter of minutes to implement this change. If you mistakenly specify a path of a script file or CSS file that doesn’t exist, the framework will gracefully handle it for you and not throw any errors.
You won’t get any runtime exceptions and the framework will continue to bundle and minify the rest of the files.
The great thing about this new feature is that you don’t need to run any tools or manually minify or bundle these files—it happens automatically when you run your application. You’re also in total control as you can switch it on and off as you need it.
This quick change easily handles bundling and minification for you and it’s definitely a step in the right direction.
NOTE This optimization will only occur under Release mode. You may notice that the files you’ve requested are not being bundled while you’re develop- ing. By default, bundling is automatically disabled under Debug mode to make life easier for the developer to read and update the code. Once you compile your application under Release mode, the optimizations take place and bundling is enabled. If you need to test this feature while in Debug mode, you can temporarily override it by setting BundleTable.Enable- Optimizations=true in your BundleConfig.cs file. This will minify and bun- dle your files while in Debug mode.
In chapter 4 we covered Expires Headers and how they notify the browser to cache static resources for a specified duration. Before a web page requests a resource, the browser first checks its cache to see if it has a resource with a matching URL. This can sometimes be problematic because as you’re developing and releasing new changes to your application, your users might have older versions of these files in their browser’s cache. One option was to force refresh of the cache using file versioning, or file rev- ving, and this appends a query string onto the end of the filename.
<link type="text/css" rel="stylesheet" href="/Styles/bootstrap.css?v=1.1">
Figure 5.3 A bundled and minified file after applying the new features in the System.Web.Optimization namespace
ASP.NET 4.5 automatically adds a hashcode to the query parameter for you.
<link type="text/css" rel="stylesheet" href="/Styles/
bootstrap.css?v=ABnfFdbAnRuas7H">
If you updated the contents of one of the files and they are bundled using the new optimization feature, a new hashcode will be appended to the end of the filename automatically. This requires no extra code and is simply handled for you.
As long as the contents of the bundle don’t change, the ASP.NET application will request the bundle using this hashcode. If any file in the bundle changes, the ASP.NET optimization framework will generate a new hashcode, guaranteeing that browser requests for the bundle will get the latest bundle and force a refresh of the cache.
Bundles also set the HTTP Expires header to expire one year from when the bundle is created. This means you’ll automatically get the benefits of HTTP caching when creat- ing your bundles.