- Load the Google font files faster by adding the
preconnecthint is supported by Chrome, Opera, Firefox and Android browsers
- Don't forget to add the
The Google Fonts performance problem
Google Fonts is a free and easy-to-use service for using high-quality fonts on your website. Many websites use Google Fonts and its 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 in the browser.
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.
The official Google Fonts embed code now includes the
If you are still using the embed code without preconnect, head over to Google Fonts, find your font and grab the latest embed code.
Interested in learning about how you improve performance of Google Fonts even more? Read Making Google Fonts Faster in 2022 by web performance consultant Sia Karamalegos.