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 = ‘http://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 (18)

  1. ken says:

    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.

  2. 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

  3. Will Peavy says:

    Nice. There’s also a Firebug extension that scans selectors: https://addons.mozilla.org/en-US/firefox/addon/10704

  4. Mike says:

    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/

  5. jack says:

    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.

  6. Yeah says:

    Yeah, if you asked further questions, you might learn something. It sounds like that might be troubling for you.

  7. Nelson says:

    @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.

  8. @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.

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

  10. Damian says:

    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.

  11. @ Giorgio Sardo, Web Technical Evangelist at Microsoft Corporation

    I do not predict a bright future to your extension and I hope it never gets popular. Personally, I have nothing against you or the people you work for.

    [Addendum: your post on such IE extension does not even explain how such extension is doing more or better than CSS-related sofwares and CSS extensions available on the web. E.g. CSSTidy]

    The nr 1 problem with web authors creating CSS code and markup code is that

    – they overdefine

    – they overdeclare

    – they over-code

    – they over use CSS code (often because they do not understand how this or that property works)

    – they use CSS resets all over

    – their CSS code gets overriden many times

    – they over-qualify selectors

    – they use descendant selector when using child selector would be sufficient

    – they generally very often abuse user system resources, parsing

    – they have zero concerns over performance, memory footprint, user system resources, parse time

    – they use universal selector (typical and often encountered in reset stylesheet is

    * {margin: 0; padding: 0;})

    "Divitis" (over-excessive use and misuse of <div> containers) and "classitis" (over-excessive use and misuse of class to style elements of an HTML document) are expressions which have been defined and explained many years ago already.

    Removing CSS rules which are not being used is, actually in the state of the web, not so much important, not so much relevant or needed in my opinion.

    The problem with the web authors these days is that they overcode and their code – no matter how bloated or ineffecient it is – is effectively being used in their webpages. Because of lack of understanding, because of lack of knowledge, because of lack of good assistive softwares, because of the omnipresence and fascination for WYSIWYG HTML editors.

    Your extension would be good if

    – it would report (eg: line number highlighted) invalid CSS declarations and point to/add the most relevant excerpt of the spec

    – it would report invalid CSS property values and point to/add the most relevant excerpt of the spec

    – it would report invalid CSS rules and give a short explanation as to why

    – it would report redefined CSS declarations

    – it would report in a clear and useful and helpful manner the browser default values of the CSS stylesheet of the browser. IIRC, Safari 4.0.4 Web Inspector does that. Reporting browser default CSS values for elements in a webpage would help, contribute to help avoid, eliminate the recourse to CSS reset stylesheets.

    – it would report CSS declarations on elements which have no impact, no effect. E.g.: span {width: 50px;} because width does not apply to inline-level (non-replaced) elements

    – it would assist learning, understanding CSS spec in general, empowering the web author, not making him more stupid, dependent on the execution of such extension

    And if one day, you develop such an IE extension, then it should first be applied to this IE blog, then to all MSDN webpages and finally to all Microsoft-controlled websites.

    regards, Gérard Talbot

  12. 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. http://www.example.com/version3) then it would truly be one of the top must-have features. Thanks for posting this!

  13. Ben says:

    A big problem I foresee with this is the extension removing hacks to deal with older versions of IE, thereby breaking sites in IE7 and IE6 (which, unfortunately we still have to test for as web developers).

  14. Internet Explorer 9 wish list:

    1) Fastest browser

    2) Download manager with ability to pause and resume, change downloading speed, etc…

    3) 100 percent successful ACID 3 test.

    4) A master password to protect passwords and stored personal data on web forms.

    5) A new tab must be launched the very next moment the new-tab button has been clicked. In IE8, new tabs launch very slow compared to other browsers.

    6) Built-in support for Windows Live, Silverlight, Windows Live Sync, Windows Live Mesh, Windows Live SkyDrive, Microsoft Security Essentials, Bing, etc

    7) Simpler bookmarking

  15. Wayne says:

    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

  16. Paul McKeown says:

    @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,

  17. Phil says:

    @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.

  18. EricLaw [MSFT] says:

    @Phil: Yes, there are absolutely factors and configurations that do slow tab opening.

    Browser add-ons are at the top of the list, but other culprits include anti-virus software, malicious software, spamming of IE Zone settings (e.g. adding thousands of sites to a given zone), or corruption of IE’s registry settings.