Twitter Feed Popout byInfofru

OverrideThis.com

Adventures in .NET Software Craftsmanship!

Bundling and Minimizing JavaScript and CSS with ASP.NET 4.5

I am in the process of getting back from the Build 2011 conference in Anaheim, California where  I got to see a ton of stuff related to Windows 8 development and designing Metro style application, and I shall blog a bit on the topic after I have had a good chance to digest all the information.  But right now, I just want to showcase one of the coolest new features of ASP.NET 4.5 “Bundling and Minimization of JavaScript and CSS”.

 

Now for those of you not familiar with the benefits of bundling and minimizing your JavaScript and CSS files, lets just say that reducing the number and raw size of web requests a browser needs to make to interact with your server is going to make your application faster.  A faster web application in most internet business scenarios equals more clients equals more money ( faster = more clients = more money).

 

So you might be asking yourself how complicated is it to setup Bundling and Minimizing of JavaScript and CSS in an ASP.NET 4.5 web application, and the short answer is, not hard at all.  You can setup bundling and minimizing in your Global.asax Application_Start to define what to bundle (See following snippet).

 

protected void Application_Start() {
    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    RegisterBundlers();
}

private static void RegisterBundlers() {

    BundleTable.Bundles.AddDefaultFileExtensionReplacements();
    BundleTable.Bundles.AddDefaultIgnorePatterns();
    BundleTable.Bundles.AddDefaultFileOrderings();

    var cssBundle = new Bundle("~/Content/css", typeof(CssMinify));
    cssBundle.AddDirectory("~/Content", "*.css", false);
    BundleTable.Bundles.Add(cssBundle);
}

 

Finally, you can modify the reference to your scripts and styles in your layout or master page to target the proper resources.

 

<link href="Styles/css" rel="stylesheet" type="text/css" />
<script src="Scripts/js" type="text/javascript"></script>

 

For more information make sure to read the ASP.NET 4.5 Preview bits release notes (here).