Oct 4, 2020
Per Djurner

Fade in Google font on load

It's been bothering me for a while now that when you load this blog you see a brief display of a fallback font before it gets replaced with the custom one (the Inter font family in my case). So, I decided to do something about it. Here's what I did.

First of all, I now tell the browser to not show a fallback font while downloading the custom one by setting font-display to block (technically this will render an invisible fallback font).

Since Google is supplying the CSS for the font we need to tell Google to use this setting though. This is done by passing the URL parameter display=block instead of the usual display=swap.

<link href="https://fonts.googleapis.com/css2?family=Inter&display=block" rel="stylesheet" />

Secondly, we can make the user experience a little nicer by fading in the custom font once it's been loaded by the browser. This is done by using the CSS Font Loading API.

The gist of it is that I set the main element to have an opacity of 0 to begin with. Then I use the Font Loading API to detect when the font has been loaded and start a CSS animation to set the opacity to 1. You can get the full details of this by viewing the source code of the example page.

Some notes to keep in mind if you decide to do something like this yourself:

  • By not showing a fallback font you're making the site less accessible. For people on slow connections it will take more time before they can start reading your website.
  • If you want to support older browsers you need to use a library that can detect when a web font has been loaded (such as Font Face Observer for example).
  • I chose to fade in the entire main element but in some cases it may make more sense for you to fade in the body element, or just the text itself.

Home