Skip to content
jshacks.dev
Browser

Load Google Fonts without blocking rendering

Load Google Fonts without blocking rendering with preconnect, a print media swap and display=swap, so the text shows in a fallback font first.

1 min read
Summarize in AI

A stylesheet in the head blocks rendering until it arrives. For Google Fonts you can keep the text visible by combining display=swap with a stylesheet that loads without blocking.

fonts.htmlHTML
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

<link rel="stylesheet"
  href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap"
  media="print" id="gf">
fonts.jsJavaScript
const sheet = document.querySelector('#gf');

function enable() {
  sheet.media = 'all';
  console.log('font stylesheet applied');
}

if (sheet.sheet) enable();
else sheet.addEventListener('load', enable);
Text
font stylesheet applied

A stylesheet with media="print" downloads at low priority and does not block rendering for screens. When it finishes, switching media to all applies it. display=swap in the URL makes each @font-face use font-display: swap, so text appears at once in the fallback and swaps when the font is ready. The preconnect links start the TLS handshake early. The crossorigin is needed on the font host.

This relies on JavaScript, so add a <noscript> copy of the normal link. Self-hosting the font files removes the third-party request entirely, and a fallback with matched metrics reduces the shift when the swap happens. See font-display.

Share

More snippets

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
Browser

Find the closest ancestor with closest

Walk up from an element to the nearest ancestor that matches a selector with closest, which includes the element itself. Works in all modern browsers.

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.