Determining which styles are in your Critical Rendering Path

Going through the slides from Ilya Grigorik‘s Velocity presentation on Optimizing the Critical Rendering Path, I saw another opportunity for automation.  It would be very tedious to take an existing site (especially one with a lot of CSS) and determine which styles were used “above the fold” by hand.  But it should be easy to determine which elements are initially in the viewport, and which styles affect them, programmatically.

the theory

  • Determine the viewport. this can be changed as necessary to meet your particular needs
  • Determine which elements are NOT in the initial viewport…
  • …and remove them.
  • Check your CSS rules to see which ones are still used. These belong in your critical rendering path.

the method

  • Make a mirror of the page.
    mkdir orig && wget -E -H -k -K -p -nH --adjust-extension
  • and a copy to play with:
    cp -r orig modified
  • make them available via HTTP any way you like.
  • execute your script and make your CSS changes:
    phantomjs aboveTheFold.js --url=
  • then test to see if there’s a difference:
    phantomjs speedreport.js --url= > tmp/orig/report.html
    phantomjs speedreport.js --url= > tmp/modified/report.html

the result

After running through the tests a few times, this approach appears to shave around 100ms off the page load time even without altering the original CSS, only moving those requests to the bottom of the body.  The script has a few obvious shortcomings and as yet did not catch every rule that I would like, but it’s a good start.

Analyzing CSS Rules

Ever wonder just how many unused CSS Rules you have laying around?  You can enumerate your stylesheets and CSS Rules in the browser for stylesheets that originate from the same domain, but that doesn’t help you much if you serve your static CSS files from a CDN.  As it turns out, you can disable the security in PhantomJS using --web-security=false.  You can then enumerate all stylesheets regardless of their domain and test to see how many elements match each selector, if any. I added a quick example to my burgeoning toolkit to create a pie chart showing each stylesheet’s rules as matched (bluish) or unmatched (redish).  The chart below was created using phantomjs --web-security=false cssCheck.js --url=

matched and unmatched CSS selectors by stylesheet

matched and unmatched CSS selectors by stylesheet

Raise your hands if you want to go faster.

Web development has reached escape velocity.  For me, personally, it has gone from a nuisance, to a hobby, to a job, to a passion.  There are entire industries built on and around the web now and the pace is accelerating.  There is a forest of information out there on how to build and optimize web apps, and it is tall and wide.  I’d like to share with you a few of the things I’ve learned along the way.

Thanks for stopping by,