This little script adds
font-display: swap; to declaration blocks returned by Google Fonts.
font-display property controls how a font should be displayed while waiting for assets to load. Typically, browsers will not display the text until the asset has loaded, which prevents a double paint where users see a flash of unstyled text (FOUT), but does result in a period where the text is invisible (FOIT).
For certain fonts, particularly icon fonts, FOIT may be preferable over FOUT, but for most body content, it is generally suggested that the content is more important than the appearance.
This script adds the
font-display: swap declaration, which causes text in that font to be displayed in fallback font until the Google font is loaded. This is optional, by adding the
?display=swap parameter; without this, the script just returns the exact same output as Google Fonts.
The reason for this script was to avoid relying on service workers required by an alternative workaround.
Wherever you would request an import of a Google font:
Instead, use your own script path, passing the appropriate parameters:
font-displayfor the Masses
font-displaydescriptor at W3C
- google/fonts#358 — outstanding issue to support this on Google Fonts
- Supercharge Google Fonts with Cloudflare and Service Workers — great workaround using service workers, discussed in the issue comments