Critical Above-the-Fold CSS for the rescue

Nowadays site loading time became a very important parameter, especially when it comes to the search engine rankings.

If you’ll test your site with Google Pagespeed tool, it will probably show that your site has some issues with content-blocking stylesheets. This means that the browser won’t paint content to the screen until your CSS has been downloaded. To fix this issue, Google recommends us to split our styles into two parts: critical (above-the-fold) and non-critical. Critical CSS should be inlined in the header meanwhile non-critical needs to be loaded asynchronously, so a user could see styled content as soon as possible.

Determining which portions of CSS are critical could be quite a tricky process. You should inspect your page at mobile, tablet and desktop sizes, to figure out which CSS rules are needed to style above-the-fold content. This seemed like a daunting task, but thanks to Scott Jehl, who created a js snippet or John Doe with his site which will help us to determine the most important styles,

When you’re done with this step and you know which styles are critical, you could start editing your stylesheets. If you use SASS and Compass, you can install the Jacket plugin, which will help you to compile styles wrapped in a special mixin into a separate file, generating critical and non-critical CSS after processing your scss files.
Installing jacket is quite a simple process, it can be done in 5 steps (assuming you are using Ruby):

Now you are ready to start using Jacket.
Let’s say, you have a _header.scss, which is used on every page of your site:

Here you can see styles for logo and navbar (which are critical, as they are always visible) and styles for the search bar and side menu (which are hidden on load, so they are non-critical). Here Jacket comes very handy – we can divide our stylesheet like so:

After processing, compass will create two files for us: critical.css and non-critical.css.




Now we have two CSS files, all we have to do is just to inline our critical.css with the means of PHP and to load our non-critical.css asynchronously (we’ll take a look at it in the next article).
So, as you can see Sass and Jacket make our lives much easier, our web-sites faster and visitors happier.

About Nick Chernichenko

Front End developer at BoyleSoftware