CSS Crunch: new IE Extension for developers

March 4th, 2010

There are many tools in the market that allow you to customize your pages’ cascading style sheets (CSS), but there are actually a very few that do the opposite—scan for all the CSS rules in the document and remove those that are not used. Cleaning out the CSS will not only reduce the bandwidth impact, but will also improve the performance of the browser (minimizing the time spent by the CSS engine to parse the style sheets).

In this post, I will describe how to build that tool using a bookmarklet and a new standard function introduced in Internet Explorer 8: document.querySelectorAll().

Let’s start with the basics: a Web page can include many cascading style sheets, each of which is composed of one or more selectors. For instance, #elementId { }, .className { }, and body{ } are each examples of selectors. Using the function querySelectorAll(), you can programmatically inspect the DOM tree and count the number of times each selector is actually used.

For instance, the following code snippet counts the number of times the CSS class Foo is used in the document:

var selectorCount = document.querySelectorAll(“.Foo”).length;

Now that we have this information, we need a way to run this script inside the document. For the purpose of this article, I didn’t want to change our server-side code.

I decided to create a bookmarklet, which is a special link that can interact dynamically with the currently loaded page. The syntax of the bookmarklet is fairly straightforward:

As you can see, at runtime this injects a remote script file that runs the analysis and displays the result.

If you scroll to the bottom of the list of CSS rules, you’ll see an option to remove temporarily unused selectors. This allow you to test if the page still displays and behaves the same way, as shown in the picture below.

I’d like to stress the fact that the goal is not to reach 100% usage on any page; there are scenarios in fact where the same style sheet could possibly be used by multiple pages and it makes sense to pre-fetch some rule, or where the page compression balance well having additional styles to maintain. Instead you should use this tool to identify possible areas for improvement.

Accept the security warning (by default, any bookmarklet is considered unsecure due to its nature)

Choose a location (for example, Favorites Bar)

Installed! You can now browse to this test page (or any other site) and click “CSS Crunch” in the Favorites Bar

This is just a starting point; if you are interested in doing more, you can find the source code here. I encourage you to look at the underlying code and customize it to suit your needs. For example, you might want to add support for multiple-pages analysis, or integration with server-side tools such as Visual Studio or IIS, or a compression capability such as Microsoft Ajax Minifier.