Web Dev Ramblings

Google Fonts - Skip a step and make your site faster

Published Tuesday, July 12, 2016

Goole Fonts is a fantastic resource to add some more interesting typography to your website, in fact this blog is using it right now. But as with so many things the method Google suggest you use is slightly less optimal than it could be. The reason: it requires two requests to the server, and one of them is render blocking.

The standard way to do it

The recommended method is to add something like this to your head tag:

<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" />

This first has to download a CSS file. The contents of that file varries over browser, which is practical IF you need to support a large number of browsers, including older ones. However if you are targeting only Modern Browsers you can skip a step and directly reference the font file(s) you need.

How we do it

For our usage here we've chosen to just link to the WOFF version, it's supported in a larger number of browsers than WOFF2, and is only marginally larger (19.77KB for WOFF vs 16.47KB for WOFF2).

@font-face { font-family: 'Open Sans'; font-style: normal; font-weight: 400; src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/cJZKeOuBrn4kERxqtaUH3T8E0i7KZn-EPnyo3HZu7kw.woff) format('woff'); }

The result

So, what's the difference between these two methods. Measuring time to fully render this page we see a result of 127 - 134 ms for the Google recommended method, and 99 - 108 ms when directly referencing the font files. The difference is 26 - 28 ms which isn't massive, but it is still wasted time for every single visitor to your page.

It's also worth noting that while our savings here are relatively low, on a higher latency connection this will be much more significant.

As an extra tip, if you can, inline the CSS to include the fonts directly into your pages, it is a tiny amount of CSS and doing so will allow the webbrowser to download them while downloading any other scripts and css files you are using on the page.

( As an added bonus, if the visitor actually has this font installed, there is no extra server request to make at all )