Dev

Fix Font Flickering On Load When Using Google Fonts

When defining the fonts you want to use for your website, you can opt to use system fonts, or use a font service like Google Fonts or Adobe Typekit.

When using a fonts service, there’s usually two ways of making the font available to the browser: you can load it remotely by using <link> tags, or you can download them from the fonts service, and upload them to the same place your website is hosted, so the font gets loaded locally.

In some cases, your only option is to have the browser load the fonts remotely.

In the following network trace, you can see that it took almost a second to have the font fetched and then loaded into the browser.

Browser fetching for fonts via API

Because of this, while the custom font is being fetched, the browser will temporarily use a system font, causing a flickering known as “Flash of Unstyled Text”, or FOUT for short.

FOUT in action on page load

Fortunately, there’s a quick fix to avoid this issue. When you embed the font by using a link tag, a loading event is triggered, which appends the .wf-loading class into each element that’s using a custom font. This class is removed as soon as the font is successfully loaded. We can take advantage of this event by adding the following CSS code to the page, which will hide the text while the font is being loaded to avoid the flickering:

html.wf-loading * {
     opacity: 0;
 }

With this fix in place I can finally stop thinking about it, and go to bed!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.