How to optimize CSS to get a perfect score on Google PageSpeed Insights

One of the rules Google PageSpeed Insights uses is Eliminate render-blocking JavaScript and CSS in above-the-fold content. This posts shows you how to pass this rule and go for a 100/100 score.

Non-blocking Javascript

To make Javascript non-blocking simply add async to your tags:

<script async src="http://your/script.js" type="text/javascript"></script>

Non-blocking Stylesheets

For CSS you need to take two steps:

  1. Create your critical (above the fold) CSS and include it inline
  2. Load other CSS via Javascript

Critical CSS

The first step is to have the minimal needed CSS to show your page and put it inline. This minimal CSS generally is everything that is needed to render the content that is above-the-fold.

Of course you can just select these styles manually and put them inline. However a far easier way is to use one of the many tools. Check Addy Osmani’s Critical-path CSS Tools project on Github for a full list.

The first time you might want to experiment using the Critical Path CSS Generator. Simply enter your url and CSS and it will output the minimal CSS to show your above-the-fold content. Next put it into a style tag on your page.

Load CSS async

To make sure your normal CSS files do not block the page load we add some Javascript that loads the CSS instead of loading it via style tags.

Use the loadCSS function as seen in the loadCSS Github project. Simply put it into a script tag on your page.

function loadCSS( href, before, media ){
  "use strict";
  var ss = window.document.createElement( "link" );
  var ref = before || window.document.getElementsByTagName( "script" )[ 0 ];
  var sheets = window.document.styleSheets;
  ss.rel = "stylesheet";
  ss.href = href;
  ss.media = "only x";
  ref.parentNode.insertBefore( ss, ref );
  function toggleMedia(){
    var defined;
    for( var i = 0; i < sheets.length; i++ ){
      if( sheets[ i ].href && sheets[ i ].href.indexOf( href ) > -1 ){
        defined = true;
      }
    }
    if( defined ){
      ss.media = media || "all";
    }
    else {
      setTimeout( toggleMedia );
    }
  }
  toggleMedia();
  return ss;
}

Next, use the function to load the needed CSS:

loadCSS("/your.css");

You can also add external CSS such as Google Fonts:

loadCSS("http://fonts.googleapis.com/css?family=Lobster");

And you’re done!