I've spent the last 2 weeks at work improving the performance of our homepage and Developer Portal with great results. One of the key optimizations was inlining our critical CSS in the HEAD of the page and asynchronously loading the full CSS.
While we do use Gulp to automate a lot of our tasks, I didn’t want to use it to sniff out the critical CSS. We use Haml to write all our HTML, and Sass for all of the CSS, so we don’t exactly have HTML pages to offer up as a source since we don’t compile them. The critical CSS Javascript snippet that most point others to is that one by Paul Kinlan, but our styles are all mobile-first, so just grabbing what is declared for Desktop using Paul’s snippet doesn’t include the earlier breakpoints that get built upon to create the Desktop layout. I needed something that would support media query detection for that reason and because we have a lot of mobile traffic, so I didn’t want to exclude those visitors. In the comments of Paul’s gist, a Github user named james-Ballyhoo posted a link to his forked version of the snippet that included media query support.
Curious how James made this work, I set about rewriting it and ensuring that it did exactly what I wanted. I wanted to be able to set my own target viewport height, include media queries, and output the resulting critical CSS in the console rather than in a box added to the page.
The main way that I use it is to copy the JS above and add it as a snippet in Chrome’s Dev Tools. I then visit the page that I need the critical CSS for and run the snippet. The CSS gets put in the console window, and it’s just a matter of copying those rules and doing a little cleanup.