Show Text While Loading Font
June 5, 2020 by Andreas Wik
If you’re using a non system font for you website, make sure you make use of this little CSS feature. For various reasons, it may sometimes take a little time for font files to be downloaded, and browsers may default to not showing any text until the font is ready, sometimes called “Flash of invisible text”.
Let’s say we’re loading the font like this in our CSS and use it for H1:
@font-face {
font-family: 'Roboto Slab';
src: url(RobotoSlab-Regular.ttf);
}
h1 {
font-family: 'Roboto Slab';
}
In some browsers, the H1 text on the page will be invisible until the font has been downloaded, then suddenly the text will appear.
If you run an audit on the page in Chrome (Open the Developer Tools with Command+Option+J on Mac and Shift+CTRL+J on Windows and find Audit in the same section where you see Console, Network etc. Hit “Generate report”.) it will flag this:
This can be fixed with just one line of CSS, namely by setting font-display to swap. This will show the text with a system font until the correct font is ready rather than hiding it.
@font-face {
font-family: 'Roboto Slab';
src: url(RobotoSlab-Regular.ttf);
font-display: swap;
}
Run another audit and this should no longer be an issue.
It’s worth to mention there are versions of browsers not supporting this feature (recent versions of Chrome, Edge, Safari and Firefox are all good). If you need to fix it for these browsers as well you may have to use something like Font Face Observer.