- Load the Google font files faster by adding the
preconnect hint is supported by Chrome, Opera, Firefox and Android browsers
- Don't forget to add the
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:
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:
<link rel="preconnect" href="https://fonts.gstatic.com/">
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
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!
<link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin>
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