How to do CSS and JavaScript Bundling and Minification in ASP.NET

ASP.NET 4.5 includes a new feature to minify and bundle CSS and JavaScript within your web application. Static content like javascript and css files contains lot of white spaces and comments. Bundling and minification improves load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript.) In the past, the recommended technique was enabling compression either using programmatically (I have a post on enabling compression in using Http Module.), or you can configure it in IIS. But it was difficult configure and has got some performance issues.

Here is a sample web application, which contains 6 style sheets and 3 javascript files, and this is network traffic before css and javascript bundling and minification.

Network Traffic without Bundling and Minification

And here is the same web application after enabling css and javascript bundling and minification.

Network Traffic with Bundling and Minification

You can enable bundling and minification using Microsoft Web Optimization framework. You can install it using nuget.

Install-Package Microsoft.AspNet.Web.Optimization

Once you install the nuget package, you can write following code in global.asax file, in the Application_Start event.

protected void Application_Start(object sender, EventArgs e)
    BundleTable.Bundles.Add(new ScriptBundle("~/bundle/scripts")
        .IncludeDirectory("~/scripts", "*.js"));
    BundleTable.Bundles.Add(new StyleBundle("~/bundle/styles")
        .IncludeDirectory("~/styles", "*.css"));

You can refer the javascript and css file in the _layout.cshtml / *.master file like this

<%@ Import Namespace="System.Web.Optimization" %>
<!DOCTYPE html>

<html xmlns="">
<head runat="server">
    <%: Styles.Render("~/bundle/styles") %>
    <form id="form1" runat="server">
    <%: Scripts.Render("~/bundle/scripts") %>

Instead of selecting all the files in the scripts / styles folder, you can also specify / order of the files like this.

BundleTable.Bundles.Add(new ScriptBundle("~/bundle/scripts")
    .Include("~/scripts/jquery-2.0.3.js", "~/scripts/jquery-ui-1.10.3.js"));

Bundling and minification is enabled or disabled by setting the value of the debug attribute in the compilation Element in the Web.config file.

  <compilation debug="false" targetFramework="4.5" />

You can override the Web.config setting with the EnableOptimizations property on the BundleTable class.

BundleTable.EnableOptimizations = true;

Happy Programming