CSS and JavaScript compression and bundling

Posted on June 20, 2010 by Frederik Vig in ASP.NET, CSS, JavaScript

In the last post in Create an EPiServer site from scratch I go through some optimization tips and tricks from YSlow. One of these are CSS and JavaScript compression and bundling of files to create fewer HTTP requests and to send the least amount of data back to the client as possible, removing whitespaces, comments etc, that we don’t need to run our code.

In the past I’ve done this as part of my deployment process, but recently I’ve come across a tool called SquishIt. Which basically is a wrapper for YUI Compressor (you can easily replace it with your compressor of choice). It is dead simple to use, you simply add a reference to SquishIt.Framework.dll in your project, and replace your old CSS and JavaScript links and script tags with code like this.

<%= Bundle.Css()
          .Add("~/Styles/screen.css")
          .Add("~/Styles/print.css")
          .Add("~/Styles/mobile.css")
          .Render("~/Styles/combined-#.css")%>
 
<%= Bundle.JavaScript()
          .Add("~/Scripts/belatedPNG-0.0.8a-min.js")
          .Add("~/Scripts/ie6.js")
          .Render("~/Scripts/ie6combined-#.js") %>

Using a fluent interface makes it easy to add more file references, ending with the Render method that takes a parameter for where to store the combined and minimized file.

It is very easy to toggle SquishIt on and off. Simply set debug=”true” in your web.config file to turn it off and render CSS and JavaScript files as normal, great for when you need to debug your code. Set debug=”false” to enable compression and bundling again.

Best part is that it only took me 2 minutes to setup and add to my current project! Works like a charm so far :).

Related Posts: