Partilhar via


CSS Crunch: new IE Extension for developers

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:

 <a href="javascript:( 
    function() {          
        var c = document.createElement('script');
        c.type = 'text/javascript';
        c.src = 'https://demos.cloudapp.net/IE/CssCrunch/Scripts/CssCrunch.js'; 
        document.getElementsByTagName('head')[0].appendChild(c); })();">            
    CSS Crunch
</a>

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

CSSCrunch being used on the IE Blog

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.

CSSCrunch being used to remove the unused style rules

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.

That’s it! You can try it here:

  1. Right click Run CSSCrunch and select “Add to Favorites”
  2. Accept the security warning (by default, any bookmarklet is considered unsecure due to its nature)
  3. Choose a location (for example, Favorites Bar)
  4. 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.

Ok, time to go! I'm checking the CSS on this blog now… :)

Have fun!

Giorgio Sardo
Web Technical Evangelist
Microsoft Corporation

Comments

  • Anonymous
    March 03, 2010
    Would be awesome to be able to run this like a profiler; start it, browse all the pages of the site, then stop it & run the analysis.

  • Anonymous
    March 03, 2010
    There's a Firefox extension that does this, and does it much better. It has multi-page automated analysis for a start, a proper UI, and it remembers data sets for later use (even exporting to CSV if desired) https://addons.mozilla.org/en-US/firefox/addon/5392

  • Anonymous
    March 03, 2010
    Nice. There's also a Firebug extension that scans selectors: https://addons.mozilla.org/en-US/firefox/addon/10704

  • Anonymous
    March 03, 2010
    I would just like to pass on my condolences, following the timely passing away of IE6. http://www.cnn.com/2010/TECH/03/04/ie6.funeral/

  • Anonymous
    March 03, 2010
    The bookmarklet doesn't work outside of IE. (instant FAIL) I'm about to view the source, but I'm curious.. does the tool compensate for valid CSS selectors that IE doesn't understand? (e.g. therefore would have no matches) That all said using a tool like this requires a good understanding of CSS, browser quirks, and the full site/application you are working on (e.g. a class used elsewhere may likely not be used on the page you are testing) This is why tools like the various extensions for Firefox work better as they work across multiple pages to get an aggregate view. PS if you are late to the game here.. developer tools for Firefox (Chrome & Safari) totally put IE's tools to shame.  If you are serious about web development you MUST use a non-IE browser as your PRIMARY development browser - anything else is ASKING for a world of hurt and embarrassment. When we hire developers we ask them what their primary development browser is.  If they answer "Internet Explorer" the interview is over and that candidate is scratched - no further questions need to be asked.

  • Anonymous
    March 04, 2010
    Yeah, if you asked further questions, you might learn something. It sounds like that might be troubling for you.

  • Anonymous
    March 04, 2010
    @Yeah - what's wrong with @jack's companies stance? I'm not sure I'd bail on the interview if a candidate said they developed primarily in IE but it would certainly be a negative response and we would further question this developers attitude towards web standards and cross-browser compatibility. More importantly we would want to ask about the developers past work - did they work on IE-only sites? (another negative), are they aware of the various IE bugs and did their designs compensate for them? More importantly being a developer is a lifetime job where you must constantly learn about new technologies and techniques.  Any developer that uses IE as their main browser for development has obviously lost touch with their development education path and has years worth of skills that need to be upgraded. I suppose if the developer was previously limited by their past employer but was willing to hit the ground running and catch up they might make it as a Jr. but for Intermediate or Senior roles they would have to be up to date in technology (which includes all the tools). Hmm that is a stumper. Would I honestly hire an IE based Web Ddevloper? I don't know.

  • Anonymous
    March 04, 2010
    @Ken: that would be great! I attached the source code, feel free to extend or change it as more appropiate :-) @James/Will: nice! Note that this bookmarklet is a proof of concept, not a "production-quality" product. There are more professional tools that do even a more in depth analysis. For instance, Expression Web allow you to check multiple pages on your back-end (not on the client), and check automatically for unused styles or undefined classes or mismatched cases. Check out this article: http://blog.thedesigndrifter.com/?p=526 @Jack: the bookmarklet should work on most browsers now.

  • Anonymous
    March 04, 2010
    What I need is an extension that will go through all of the extraneous style tags, compare their contents, and assign classes based on these styles to each of the tags. (normalizing the style classes tags as it were)

  • Anonymous
    March 04, 2010
    I think it's great Microsoft is pushing forward IE as a web development platform, keep bringing on improvements and promoting extensions! However, the fact of the matter is that Firefox is the de-facto developers platform and it's tools have had years to mature where the IE platform was doing nothing. If you really wanna take on Firefox as a good development platform then you need to push the developers toolbar to a whole new level and really compete with Firebug rather than just sort of lazily following down it's path.

  • Anonymous
    March 04, 2010
    The comment has been removed

  • Anonymous
    March 04, 2010
    Awesome script though this would be truly useful if we could have the script do this after viewing numerous pages. Additionally there are a lot of CSS selectors that are specific to AJAX content on the next version of my site. If IE9 could have this feature built in to index used selectors and compile a list over time for a domain/path (e.g. www.example.com/version3) then it would truly be one of the top must-have features. Thanks for posting this!

  • Anonymous
    March 04, 2010
    The comment has been removed

  • Anonymous
    March 04, 2010
    The comment has been removed

  • Anonymous
    March 05, 2010
    Maybe you should not waste so much time on rubbish like this when there are much better extensions for Firefox that do a much better job and you should focus on the performance of your browser: "This brings us to Internet Explorer, Destroyer of Netscape Navigator. The browser from Redmond finished last no less than fourteen times (more than half of the tests). Internet Explorer's performance here is nothing less than sad." http://www.tomshardware.com/reviews/firefox-chrome-opera,2558-10.html

  • Anonymous
    March 05, 2010
    @Sachin Joseph Your list is off-topic, but seeing you brought it up, I consider your idea of built-in support for Windows Live, Silverlight, etc., nightmarish, and I'm certain that Microsoft is not so stupid as to go down such a route.  The user should decide whether or not he wishes to use these products or services and hence support should be optional; anyway it might be seen as anti-competitive.  If you have all sorts of these running in your browser, this might explain why you find new tabs launch slowly.  Just a thought. Regards,

  • Anonymous
    March 09, 2010
    @Sachin... "5) A new tab must be launched the very next moment the new-tab button has been clicked." It pretty much is the next moment, generally :-)   @Paul - I've done clean installs of the OS and IE 7 and 8, security patched, and then had tabs take 1-2 seconds to open with no plugins loaded.  It isn't an urban myth, it's real.

  • Anonymous
    March 09, 2010
    The comment has been removed