Faster Google Fonts with Preconnect

Summary

  • Load the Google font files faster by adding the preconnect hint
  • The preconnect hint is supported by Chrome, Opera, Firefox and Android browsers
  • Don’t forget to add the crossorigin attribute!

The Google Fonts performance problem

The CDN Planet website uses the Roboto font, powered by the free and easy to use Google Fonts.

Google Fonts is a very reliable service and network performance is generally great (the service lives on Google’s global CDN).
But yet, there is one problem with Google Fonts performance: the font files start downloading late.

The waterfall chart below shows the performance problem in action:

waterfall cdnplanet before preconnect

The CSS loads first, then the font files.
This behavior is not so great for performance but quite logical: the URLs of the font files are in the CSS file, so the browser must first download and parse the CSS.

Luckily, Google always serves the fonts from the same domain, fonts.gstatic.com, and you can instruct the browser to ‘preconnect’ to that domain while it is loading the CSS!

The preconnect hint

Preconnect is one of the Resource Hints as defined in the W3C Working Draft:

The preconnect link relation type is used to indicate an origin that will be used to fetch required resources. Initiating an early connection, which includes the DNS lookup, TCP handshake, and optional TLS negotiation, allows the user agent to mask the high latency costs of establishing a connection.

Preconnect is supported by most browsers and improves Google Fonts performance.

Preconnect done wrong

Implementing preconnect is simple: add the preconnect hint to the head section of the HTML:



waterfall cdnplanet after preconnect no crossorigin

Hmmm, Chrome performs the DNS lookup only. Why does the browser not also establish the (secure) connection?

The answer is simple: I did not add the crossorigin attribute to the link element.

Ilya Grigorik explains why this attribute is needed in his excellent article Eliminating Roundtrips with Preconnect

The font-face specification requires that fonts are loaded in “anonymous mode”, which is why we must provide the crossorigin attribute on the preconnect hint: the browser maintains a separate pool of sockets for this mode.

Preconnect done right!


waterfall cdnplanet after preconnect with crossorigin

Excellent!
DNS, TCP and TLS happens in parallel with the loading of the Google Fonts CSS file.
We effectively improved Google Fonts performance by reducing the load time by ~ 100 milliseconds.

Learn more about webfont performance

CDN Planet