Frederik Vig – ASP.NET developer

Follow me

Posts tagged ‘Performance’

CSS and JavaScript compression and bundling

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 :) .

Measuring JavaScript performance

According to Response Time overview, the response time for JavaScript code to execeute should be no more than 0.1 seconds (100 milliseconds). Especially on JavaScript/Ajax heavy sites this can be a problem. That’s why it is always good thing to check the performance of your code.
To measure your JavaScript you can use the code below:

function somefunction() {
    var start = new Date().getMilliseconds();
    // code here
    var stop = new Date().getMilliseconds();
    var executionTime = stop - start;
    console.log("Execution time " + executionTime +
        " milliseconds"); // or alert("Execution time " + executionTime + " milliseconds");
}

Note that Firebug for Firefox also has a code profiler which does the same thing. To use it install Firebug, enable firebug (f12), activate the console window, press the profile button, refresh the page, click the profile button again (more information: Firebug JavaScript Debugger and Profiler).
Firebug profiler

© Copyright Frederik Vig. Based on Fluid Blue theme