“Below the fold” CSS on websites

By Evasive Software
On July 19, 2015
In Blog

According to “Page speed insights” by Google, the fastest and best performing way of handling big stylesheets on a modern website, is to “inline” critical properties within the <head> element, and then, asynchronously load the remaining style rules later.

While this sounds reasonable, executing this reliably and cleanly can get tricky, especially if you have multiple stylesheets.

A scenario

When developing the new Evasive Software site, we wanted to really push how far we could take the performance of a WordPress website.

After the usual tricks such as caching, image compression, and client side caching rules were set, we focused on pushing that Page speed insights score as close to 100 as we could get it.

Our biggest score reducer was the fact we were synchronously loading a global stylesheet within <head>. This means, the browser can not render any content until this asset has loaded.

To handle our inline stylesheets and asynchronous loading of our external CSS files, we decided to write a small piece of javascript to help us out.

Meet btf.js

btf.js is a small javascript library that will take parameters from your inline “above the fold” <style> element to dynamically and asynchronously load the remaining stylesheets on your site.

Using btf.js

The first step you should take to load your CSS in this method, is to create a rule set for “above the fold” css content. This means, anything that will be rendered and visible when a user lands on your page without scrolling.

  1. Remove any synchronous <link> elements from your site.
  2. Add a new <style id="atf" type="text/css> element in <head>, and add your inline style data here.
  3. Add a list of external stylesheets you wish to load to the new “atf” <style> element by using the guide below. Use ; to separate each url.
  4. Add the btw.js script just before </body>, with the asynchronous flag.

Example 1

<style id="atf" data-btf="style.css;second-style.css;" type="text/css">body { background: red; color: black; } </style>

<script async src="btf.js"></script></body>

Example 2

<style id="atf" data-btf="http://fonts.googleapis.com/css?family=Open+Sans;style.css;" type="text/css">body { font-family: 'Open Sans', Open Sans, Arial, sans-serif; } </style>

<script async src="btf.js"></script></body>

 

The results

By writing and utilising btf.js, it allows us to easily integrate third party stylesheets and keep an extremely fast page load speed. The results speak for themselves.

results-btw.js

Blog comments powered by Disqus