Skip to content
jshacks.dev
Performance

Load fonts with font-display swap

Show text in a fallback font while a web font loads by setting font-display swap, or load the font with the FontFace API and add it when it is ready.

1 min read
Summarize in AI

By default a browser may hide text for a few seconds while a custom font downloads. font-display: swap shows a fallback font first and switches when the font arrives.

fonts.cssCSS
@font-face {
  font-family: 'Inter';
  src: url('/fonts/inter.woff2') format('woff2');
  font-display: swap;
}

The same can be done from JavaScript with the FontFace API, which lets you control when loading starts:

fonts.jsJavaScript
const inter = new FontFace('Inter', 'url(/fonts/inter.woff2)', { display: 'swap' });

await inter.load();
document.fonts.add(inter);
console.log(inter.status, document.fonts.check('16px Inter'));
Text
loaded true

swap gives the fastest first paint but can cause a visible shift when the real font replaces the fallback and the text reflows. Reduce it by choosing a fallback with similar metrics, using size-adjust and the other descriptors in @font-face, and by preloading the font file with <link rel="preload" as="font" type="font/woff2" crossorigin>.

optional is another value: the font is used only if it arrives very quickly, which avoids the shift entirely at the price of showing the fallback on a slow first visit. Use WOFF2, which is the smallest format. See font-display.

Also inBrowser
Taggedcss
Share

More snippets

Performance

Time code with performance.now

Time a block of code with performance.now, which returns a monotonic high-resolution timestamp in milliseconds, and avoid the clock jumps Date.now can have.

1 min read
APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.