Skip to content

Lesson 44 of 52Performance and tooling

Loading Fonts and Images Fast

Ship fonts and images that load fast and do not shift: font-display, preload with crossorigin, subsetting, fallback metrics, AVIF, sizes, priority and image CDNs.

25 min read0/4 questions

A product page fails LCP on mobile. You open the Network panel and find the usual suspects: six font files (regular, italic, medium, semibold, bold and a second family for one heading) adding up to 400 KB, all requested late, and a 2.4 MB hero JPEG that a 390-pixel-wide phone downloads in full. When the fonts finally arrive, every paragraph rewraps and the "Add to basket" button jumps down the page. Fonts and images are usually most of a page's bytes and the cause of most LCP and CLS problems, and they are fixed in HTML and CSS, not in JavaScript. This lesson builds on Core Web Vitals and Page Speed and on Typography, and gives you the specific fixes. Framework helpers like next/font and next/image automate many of these; knowing what they do underneath is what lets you debug them.

Why web fonts are late

A font is the last resource in a chain. The browser cannot know which font files it needs until it has the HTML, downloaded and parsed the CSS, and found text on the page that actually uses a given @font-face. Only then does it request the file. With a hosted service like Google Fonts the chain is longer, because the CSS itself lives on another origin:

Loading a Google Font with no hints
Browseryour-site.comfonts.googleapis.comfonts.gstatic.comGET /HTMLGET /css2?family=Inter@font-face rulesGET inter.woff2font file

The HTML arrives and the parser finds a stylesheet link to Google Fonts.

1/6

The old argument for Google Fonts was a shared cache: a visitor might already have Inter from another site. That stopped being true around 2020, when browsers started partitioning the HTTP cache by the top-level site, to stop sites tracking users through cache timing. A font cached on site A is downloaded again on site B. So for performance, self-hosting is usually better: one origin, no extra connections, your own cache headers, and no third party seeing your visitors' IP addresses (a GDPR concern that has come up in European courts). If you do keep a third-party font service, add <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> so the connection is ready before the font is requested.

font-display: what text does while it waits

font-display in each @font-face rule controls what happens before the font arrives. It works with two periods: a block period, when text using the font is drawn invisible, and a swap period, when the fallback is shown and the web font swaps in if it arrives. After both, the browser keeps whatever it has.

ValueBlock periodSwap periodEffect
autoBrowser decidesBrowser decidesUsually behaves like block
blockShort, about 3 sForeverInvisible text (FOIT) until the font loads. Delays LCP if the LCP element is text
swapTiny, about 100 ms or lessForeverFallback text at once, swaps whenever the font arrives. Good for LCP, risky for CLS
fallbackTinyShort, about 3 sSwaps only if the font arrives fairly quickly, otherwise keeps the fallback for this page view
optionalTinyNoneUses the font only if it is ready almost immediately (usually cached or preloaded). No font-caused shift at all

The trade-off is between brand and stability. swap is the common default, since text is readable at once, but a late swap with a mismatched fallback causes the layout shift you saw in the scenario. optional gives zero font shift and great LCP, at the cost that a first-time visitor on a slow connection may see the fallback for that whole page view (the font is cached for the next one). For body text on content sites, optional plus a preload is a strong choice. For a logo-like display font where the brand look matters, swap with matched fallback metrics (below) is the usual answer. Icon fonts should use block, since a fallback letter in place of an icon is meaningless, or better, be replaced with SVG.

Preload, and why it needs crossorigin

A preload tells the browser to fetch the font immediately, in parallel with the CSS, instead of discovering it at the end of the chain:

<link rel="preload" href="/fonts/inter-latin-var.woff2" as="font" type="font/woff2" crossorigin>

Every attribute matters. as="font" sets the right priority and request type. type lets a browser skip formats it does not support. And crossorigin is required even for a font on your own origin. Fonts are always fetched in CORS mode (anonymous credentials). A preload without crossorigin is made in a different mode, so when the CSS later asks for the font, the browser cannot reuse the preloaded response. It downloads the file a second time, and the console warns that a preloaded resource was not used. This is one of the most common font bugs in production, and it makes things slower than having no preload at all.

Preload only what the first screen needs, typically one or two files: the body text weight and maybe the heading weight. Every preload competes for bandwidth with the LCP image and the CSS. Preloading five fonts usually makes LCP worse.

Quick check
Your head contains <link rel="preload" href="/fonts/body.woff2" as="font">. The Network panel shows body.woff2 downloaded twice. Why?
Need a nudge? A hint rules out a wrong answer.

Fewer font bytes

The cheapest font byte is the one you never send.

  • WOFF2 only. It is compressed with Brotli and supported by every current browser. You do not need WOFF, TTF or EOT fallbacks in a modern src list.
  • Fewer families and weights. Each weight and style is a file. Two families and three weights is plenty.
  • Variable fonts. One variable file covers a whole range of weights (font-weight: 100 900). It is larger than any single static weight, so it wins when you use three or more weights, and loses if you only ever use regular and bold.
  • Subsetting. A full font with every script can hold thousands of glyphs. If your site is in English, ship only the Latin subset. pyftsubset from the fontTools Python package does this:
pip install fonttools brotlipyftsubset Inter-Variable.ttf --unicodes="U+0000-00FF,U+2000-206F,U+20AC,U+2122" --flavor=woff2 --layout-features="*" --output-file=inter-latin-var.woff2

Tools such as glyphhanger report which characters your pages actually use. Subset carefully: user names and translated pages use characters you did not plan for.

unicode-range makes subsets safe. You split the font into several files and declare each with the same family name and a unicode-range. The browser downloads a file only if the page's text contains a character in its range. This is exactly how Google Fonts serves fonts, and you can do the same when self-hosting.

@font-face {
  font-family: "Inter";
  src: url("/fonts/inter-latin-var.woff2") format("woff2");
  font-weight: 100 900;
  font-display: swap;
  unicode-range: U+0000-00FF, U+2000-206F, U+20AC;
}
@font-face {
  font-family: "Inter";
  src: url("/fonts/inter-latin-ext-var.woff2") format("woff2");
  font-weight: 100 900;
  font-display: swap;
  unicode-range: U+0100-024F, U+1E00-1EFF;
}

Here is the matching logic as code. A page that mentions a Polish city pays for one extra file; a page that does not, never downloads it.

JavaScriptunicode-range.js
// Three @font-face rules for one family, split by unicode-range (like Google Fonts serves)const faces = [ { file: "inter-latin.woff2", ranges: [[0x0000, 0x00ff], [0x2000, 0x206f], [0x20ac, 0x20ac]] }, { file: "inter-latin-ext.woff2", ranges: [[0x0100, 0x024f], [0x1e00, 0x1eff]] }, { file: "inter-greek.woff2", ranges: [[0x0370, 0x03ff]] },]; // The browser downloads a face only if the page's text uses a character in its rangefunction filesFor(text) { const used = new Set(); for (const ch of text) { const cp = ch.codePointAt(0); for (const face of faces) { if (face.ranges.some(([lo, hi]) => cp >= lo && cp <= hi)) used.add(face.file); } } return [...used];} console.log(filesFor("Pricing plans from 9 euros a month"));console.log(filesFor("Pricing for Kraków and Łódź"));console.log(filesFor("Price: 9 € (Δ +2%)"));
Output
Press Run (⌘ Enter) to see what happens.

Matching fallback metrics to stop the shift

Every font has its own metrics: average character width, ascent (height above the baseline), descent and line gap. If your fallback (say Arial) is wider than your web font, a paragraph that was six lines in Arial becomes five lines in the web font, and everything below moves up when the swap happens. The fix is to adjust the fallback so it takes the same space, using descriptors in an @font-face rule that wraps a local font:

@font-face {
  font-family: "Inter Fallback";
  src: local("Arial");
  size-adjust: 107%;       /* scale glyph widths to match Inter's */
  ascent-override: 90%;    /* match the space above the baseline */
  descent-override: 22%;   /* match the space below it */
  line-gap-override: 0%;
}
 
body {
  font-family: "Inter", "Inter Fallback", sans-serif;
}

The numbers above are illustrative. Real values come from the two fonts' metric tables, and tools calculate them for you: next/font generates this rule automatically, and Fontaine and Capsize do the same for any build setup. size-adjust is supported in every current browser. The three -override descriptors are not Baseline yet (Safari is the gap at the time of writing), so Safari users get matched widths but slightly different line heights. Check MDN for current support.

Try it. The blue text stands in for the web font, the red text is your local Arial (or Helvetica) wrapped in an @font-face with size-adjust. Drag the slider until the widths match.

HTML & CSS
<style id="face"></style><style> .stage { position: relative; max-width: 340px; font-size: 18px; line-height: 1.5; } .stage p { margin: 0; } .web { font-family: "Times New Roman", Times, serif; color: rgba(0, 0, 200, 0.85); } .fallback { font-family: "Matched Fallback"; color: rgba(220, 0, 0, 0.55); position: absolute; top: 0; left: 0; right: 0; } #out { font: 13px/1.5 ui-monospace, monospace; margin-top: 12px; white-space: pre-wrap; }</style><label>size-adjust on the fallback: <input id="size" type="range" min="70" max="110" value="100"> <span id="val"></span></label><div class="stage"> <p class="web" id="web">Fonts often arrive late. If the fallback font takes more or less room than the real one, lines rewrap when the swap happens. Every line below moves with them.</p> <p class="fallback" id="fb" aria-hidden="true">Fonts often arrive late. If the fallback font takes more or less room than the real one, lines rewrap when the swap happens. Every line below moves with them.</p></div><p id="out"></p><script> // Blue: the "web font" (Times New Roman stands in for it). // Red: the fallback, your local Arial or Helvetica, with size-adjust applied. const size = document.getElementById("size"); const probe = (family) => { const s = document.createElement("span"); s.style.cssText = `font: 18px ${family}; position: absolute; white-space: nowrap; visibility: hidden`; s.textContent = "The quick brown fox jumps over the lazy dog"; document.body.append(s); const w = s.getBoundingClientRect().width; s.remove(); return w; }; function update() { document.getElementById("face").textContent = `@font-face { font-family: "Matched Fallback"; src: local("Arial"), local("Helvetica"), local("Liberation Sans"); size-adjust: ${size.value}%; }`; document.getElementById("val").textContent = size.value + "%"; document.fonts.ready.then(() => { const ww = probe('"Times New Roman", Times, serif'); const fw = probe('"Matched Fallback"'); document.getElementById("out").textContent = `one line of text: web font ${ww.toFixed(0)}px wide, fallback ${fw.toFixed(0)}px wide` + (Math.abs(ww - fw) < 3 ? "\nAverage widths match. Single words still differ, so a few lines may break differently: close, not exact." : ""); }); } size.oninput = update; update();</script>

Preview

On most systems the widths meet at around 92%. Even then the lines do not overlap perfectly: individual letters differ, and the text sits at a slightly different height. That vertical difference is what ascent-override and descent-override fix.

Image formats and quality

For photos, AVIF usually produces the smallest file at a given visual quality, WebP is a close second with faster encoding, and JPEG is the universal fallback. All three are supported in every current major browser, so for most sites the choice is AVIF first with a JPEG or WebP fallback through <picture>, as you saw in Images and Media. A few practical points seniors know:

  • Quality settings are not comparable across formats. AVIF at quality 50 is not "worse" than JPEG at 80. Compare visually, or with a metric like SSIM or DSSIM, at the size the image is displayed.
  • AVIF encodes slowly. Fine at build time or in an image CDN with caching, painful if you encode on every request.
  • Dimensions matter more than format. A correctly sized JPEG beats an AVIF four times too large. Resize first, then pick the format.

sizes done right

The most common responsive image bug is a missing or wrong sizes. The browser picks a srcset candidate before layout, while it is still parsing HTML, so it cannot know how wide the image will be. sizes tells it. Without sizes, the browser assumes 100vw: the image is as wide as the whole viewport. For a 400-pixel card on a 1440-pixel desktop screen at 2x, that means downloading a 2,880-pixel image to show at 400.

Here is a simplified model of the selection: the slot width from sizes, times the device pixel ratio, then the smallest candidate at least that wide.

JavaScriptsrcset-choice.js
// A simplified model of how a browser picks from srcset.// Real browsers may also reuse a larger cached file or save data on slow networks.const candidates = [400, 800, 1200, 1600, 2400]; // the w descriptors in srcset function slotWidth(sizes, viewport) { for (const { media, width } of sizes) { if (media === null || viewport <= media) { return width.endsWith("vw") ? (parseFloat(width) / 100) * viewport : parseFloat(width); } }} function pick(sizes, viewport, dpr) { const slot = slotWidth(sizes, viewport); const needed = slot * dpr; const file = candidates.find((w) => w >= needed) ?? candidates.at(-1); return `${viewport}px wide at ${dpr}x: slot ${slot}px, needs ${needed}px, downloads ${file}w`;} // Cards: full width up to 600px, two columns up to 900px, then a fixed 400pxconst good = [ { media: 600, width: "100vw" }, { media: 900, width: "50vw" }, { media: null, width: "400px" },];const missing = [{ media: null, width: "100vw" }]; // no sizes attribute means 100vw console.log("With sizes:");console.log(pick(good, 390, 3));console.log(pick(good, 1440, 2));console.log("Without sizes:");console.log(pick(missing, 390, 3));console.log(pick(missing, 1440, 2));
Output
Press Run (⌘ Enter) to see what happens.

The phone result is the same either way, because on a phone the card really is full width. The desktop result is three times the bytes. The bug hides because phone testing shows nothing wrong. Write sizes from your CSS layout: (max-width: 600px) 100vw, (max-width: 900px) 50vw, 400px mirrors the breakpoints above. Lazy-loaded images can use sizes="auto" in Chromium browsers, which measures the real layout width since the image is loaded after layout anyway; keep an explicit fallback list after it for other browsers, and check current support before relying on it.

Predict the outputHTML

The viewport is 1280px wide at 1x, and the image is displayed 400px wide by CSS. Which file does the browser download?

<img
srcset="card-400.avif 400w, card-800.avif 800w,
        card-1600.avif 1600w, card-2400.avif 2400w"
src="card-800.avif"
width="400" height="300" alt="...">
Need a nudge? Hints walk you through it.

Priority hints and lazy loading

The loading attributes are small, but they decide the order bytes arrive in.

  • loading="lazy": for images below the fold. Never on the LCP image, and in practice not on anything likely to be in the first viewport on common screen sizes. A lazy image's request waits for layout, which is exactly the "resource load delay" in the LCP breakdown.
  • fetchpriority="high": on the LCP image, so it is not queued behind other images that start at low priority. One or two per page. You can also lower the priority of above-the-fold images that do not matter, like the second and third slides of a carousel, with fetchpriority="low".
  • decoding="async": lets the browser decode the image off the critical path instead of holding up the paint of other content. A small win for large images; leave it off the LCP image if you see it painting later.
  • Preloading responsive images: when the LCP image cannot be in the HTML (a CSS background, or JavaScript-rendered), preload it with the same candidates: <link rel="preload" as="image" imagesrcset="..." imagesizes="..." fetchpriority="high">.

Image CDNs and art direction

Producing four widths in two formats for every image by hand does not scale. An image CDN (Cloudinary, imgix, Cloudflare Images, Vercel's image optimisation and others) resizes, converts and caches on request, controlled by the URL, for example /cdn/w_800,f_auto,q_auto/hero.jpg. f_auto-style options pick the format from the browser's Accept header, which means the CDN must send Vary: Accept so caches do not serve AVIF to a browser that asked for JPEG. Check the exact URL syntax in your provider's documentation. Two cautions: an open transform endpoint can be abused to generate unlimited variants (restrict allowed widths and source domains), and you still need to write sizes yourself, because no CDN knows your layout.

Art direction is a different problem from resolution switching. Sometimes a phone should not get a smaller copy of the desktop image, but a different crop: a tight square of the product instead of a wide banner where the product is a speck. That is what <source media="..."> inside <picture> is for. The browser must use the first source whose media query matches, which makes this deterministic, unlike srcset, where the browser is free to choose.

HTML & CSS
<style> img { max-width: 100%; height: auto; display: block; } #out { font: 13px/1.5 ui-monospace, monospace; margin-top: 8px; }</style><!-- Change max-width: 500px to 2000px to force the phone crop here --><picture> <source media="(max-width: 500px)" srcset="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3Crect%20width='300'%20height='300'%20fill='skyblue'/%3E%3Crect%20y='230'%20width='300'%20height='70'%20fill='seagreen'/%3E%3Ccircle%20cx='150'%20cy='150'%20r='90'%20fill='tomato'/%3E%3Ctext%20x='16'%20y='40'%20font-size='26'%20font-family='sans-serif'%3Esquare%20crop%3C/text%3E%3C/svg%3E" width="300" height="300"> <img src="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20640%20240'%3E%3Crect%20width='640'%20height='240'%20fill='skyblue'/%3E%3Crect%20y='180'%20width='640'%20height='60'%20fill='seagreen'/%3E%3Ccircle%20cx='320'%20cy='120'%20r='50'%20fill='tomato'/%3E%3Ctext%20x='20'%20y='40'%20font-size='28'%20font-family='sans-serif'%3Ewide%20crop,%208:3%3C/text%3E%3C/svg%3E" width="640" height="240" alt="A red ball resting on grass under a blue sky" id="hero"></picture><p id="out"></p><script> const hero = document.getElementById("hero"); const show = () => { const crop = hero.currentSrc.includes("square") ? "square crop from the source" : "wide crop from the img"; document.getElementById("out").textContent = `viewport ${innerWidth}px: browser chose the ${crop}`; }; hero.onload = show; addEventListener("resize", show);</script>

Preview

Notice the width and height on the source. Different crops have different aspect ratios, and putting dimensions on each source lets the browser reserve the right space for whichever one it picks, so art direction does not cost you CLS. Open the preview full screen and narrow it to watch the crop switch.

Match the pairs0/5 matched

Match each finding in a page audit to its fix.

Choose an item, then its match on the other side.

Measuring what you fixed

Check each fix in DevTools, in a throttled run, before you trust it. In the Network panel, filter by Font and Img, enable the Priority column, and read the waterfall: fonts should start early (preloaded) and appear once each; the LCP image should start near the top with High priority; no image should be far wider than its displayed size. In the Performance panel, the LCP marker shows which element was the LCP and the breakdown of its time, and the Layout Shifts track shows whether a font swap moved anything. The Coverage tab and a quick search of your CSS for font-weight values tell you whether you load weights nobody uses. Browser DevTools for HTML, CSS and Performance goes deeper on all of these panels.

Put it in order5 steps

Order these steps for fixing a slow hero image, starting with the first thing to check.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
font-display
An @font-face descriptor setting the block and swap periods: what text shows while a web font loads.
FOIT and FOUT
Flash of invisible text (block) and flash of unstyled text (swap): the two ways a late font shows itself.
cache partitioning
Browsers key the HTTP cache by top-level site, so a file cached on one site is downloaded again on another.
unicode-range
An @font-face descriptor that limits a font file to certain characters, so it downloads only when the page uses them.
size-adjust
An @font-face descriptor that scales a font's glyphs, used to make a local fallback match a web font's width.
sizes
An img attribute telling the browser the displayed width before layout. Missing means 100vw, which over-downloads.
art direction
Serving a different crop or composition per screen size with picture and source media, not just a different resolution.