Avoid invisible text during font loading

Font files are usually relatively large files and take a while to load. To get around this, some browsers hide the text until the font is loaded (“invisible text”). If you want to optimize performance, avoid “invisible text flicker” and use the system font (“unstyled text”) to display content to the user immediately.

This article introduces two methods in total. The first method is very simple, but cannot be supported by all browsers; the second method is slightly more troublesome, but compatible with all browsers.

Method 1. Use font-display

Example:

@font-face { font-family: Helvetica; }

Change the above to:

@font-face { font-family: Helvetica; font-display: swap; }

font-displayis an API for specifying font display policies. swapText that tells the browser to use this font should be displayed using the system font immediately. After the custom font is loaded, replace the system font.

If the browser does not support font-displayit, the browser will continue to follow its default behavior to load the font.

The following are supported by major browsers font-display:

EdgeUse the system font until the font is ready and then change the font.
ChromeHide the text for up to 3 seconds, if the text is still not ready, use the system font until the custom font is ready, then change the font.
FirefoxSame as Chrome.
SafariHide text until the custom font is ready.

Method 2. Use the FontFaceObserver library

With a little more work, it should work fine on all browsers.

This method consists of three parts:

  • Do not use custom fonts on initial page load. This ensures that the browser uses the system font to display the text immediately.
  • Automatically detect when custom fonts are loaded. This can be done through the FontFaceObserver library with just a few lines of JavaScript code.
  • Update page styles to use custom fonts.

For the usage of FontFaceObserver , please refer to: https://github.com/bramstein/fontfaceobserver

Leave a Comment