gfont-swap

This little script adds font-display: swap; to declaration blocks returned by Google Fonts.

The 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.

Usage

Install the script on a server with gzip and ideally brotli support (see php-ext-brotli).

Wherever you would request an import of a Google font:

@import url('https://fonts.googleapis.com/css?family=Roboto:300,300i,400');

Instead, use your own script path, passing the appropriate parameters:

@import url('https://example.com/gfont-swap/?family=Roboto:300,300i,400&display=swap');

Further reading