Use localStorage to save font files as data URIs to load fonts faster without any flicker

A clever way to avoid the flicker that a custom font introduces

The idea is to only load a font from the server once. Then we store the data into the localStorage. On subsequent requests we load the font directly from localStorage. This eliminates the flashing on subsequent page loads. Only the first load is affected by the flashing.

Overview of the script

1. We let the old browsers stop early. Testing for window.addEventListener or some knows user agents (older Android stock browser, Opera Mini, etc.) is good enough.

2. In some cases localStorage can be unreachable, although the browser supports WOFF fonts. For theses cases I provide some fallback.

3. Then we check whether the font is already stored in localStorage. If it is, we load it immediately.

4. If it hasn’t been loaded before, we load it with an AJAX call. But first we check for WOFF2 support.

5. Then we store the data into localStorage and load the css text into a style element.

Read full article at bdadam.com