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 http://fasterness.com
  • 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=http://fasterness.com/example/crp/orig/
  • then test to see if there’s a difference:
    phantomjs speedreport.js --url=http://fasterness.com/example/crp/orig/ > tmp/orig/report.html
    phantomjs speedreport.js --url=http://fasterness.com/example/crp/modified/ > 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.