Frontend development · Intermediate · 22 min
Load web fonts without layout shift
By Padding · Updated 18 Nov 2026
Modern browsers · CSS Fonts Level 4 and 5 (font-display, size-adjust) · checked in Chromium 159 · Node.js 26
You will self-host the Larkfield Clinic typeface as one subset WOFF2 file that still covers Yoruba, Hausa, Igbo and Akan letters, preload it, pick a font-display value and tune a fallback font with size-adjust, then measure the page's layout shift falling to near zero.
On this page
A web font arrives after the page's first paint. Until it does, the browser draws the text in a fallback font, and when the real one lands it redraws. If the two fonts are different widths, lines wrap at different words, paragraphs gain or lose a line, and everything under them jumps. Visitors lose their place, tap the wrong button, and the jump counts against Cumulative Layout Shift (CLS), one of Google's Core Web Vitals.
You will fix that on the Home screen of Larkfield Clinic, the fictional community clinic whose booking app uses Inter. You will measure the jump first, then make four changes: cut the font file down to the characters the clinic needs, preload it, choose how the browser behaves while it waits, and reshape a local fallback font so it takes up the same space as Inter. The measurement at the end shows the difference in bytes and in layout shift.
The subsetting step has a twist that matters for a clinic serving Lagos as much as London. Ready-made "Latin" subsets usually leave out the letters Yoruba, Hausa, Igbo, Akan and Ewe need, such as ẹ, ọ, ṣ, ɓ, ɗ, ƙ, ɛ and ɔ. When a letter is missing, the browser borrows it from another font, so names and greetings show up in a mix of typefaces. You will build a subset that keeps them.
Step 1 · Set up the project
Make a demo folder and install the tools at pinned versions. inter-ui is a package of the Inter font files. subset-font cuts fonts down, fontkit reads them, the two @capsizecss packages provide font measurements, and Playwright drives a real browser so you can measure layout shift from a script:
mkdir -p ~/font-shift-demo
cd ~/font-shift-demo
npm init -y > /dev/null
npm install --save-exact inter-ui@4.1.1 subset-font@2.9.0 fontkit@2.0.4 @capsizecss/unpack@4.0.1 @capsizecss/metrics@4.5.0 playwright@1.65.1
npx playwright install --with-deps chromiumOn Linux, --with-deps also installs the system libraries and fonts Chromium needs, so it may ask for your sudo password. On macOS and Windows it downloads the browser only.
Copy the full Inter variable font into a fonts folder. A variable font holds every weight in one file, which is why the page needs only one font file:
cd ~/font-shift-demo
mkdir -p fonts
cp node_modules/inter-ui/variable/InterVariable.woff2 fonts/
ls -l fontsInter is released under the SIL Open Font License, which allows self-hosting and subsetting. Check the licence of any other typeface before you modify or serve it yourself.
Check it worked
ls -l fonts lists InterVariable.woff2 at about 350 KB (352,240 bytes for Inter 4.1.1), and npx playwright --version prints Version 1.65.1.
Step 2 · Build the page the usual way
Create the Home screen with the clinic's address, a greeting in three Nigerian languages, a short introduction, the five services and the booking button. The font is loaded the way many sites do it: one @font-face rule pointing at the full file, and Arial as the fallback:
cd ~/font-shift-demo
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Larkfield Clinic</title>
<link rel="stylesheet" href="fonts.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<h1>Larkfield Clinic</h1>
<p class="muted">14 Mill Lane</p>
<p class="muted"><span lang="yo">Ẹ káàbọ̀</span> · <span lang="ha">Barka da zuwa</span> · <span lang="ig">Nnọọ</span></p>
<p>Book online at any time of day. Choose a service, pick a time and add your details. We text you to confirm and again the day before.</p>
<h2>Our services</h2>
<ul>
<li><strong>GP appointment · 10 min</strong> For a new health problem, a worry that will not go away or a sick note.</li>
<li><strong>Nurse appointment · 15 min</strong> Dressings, stitches out, blood pressure checks and help with long-term conditions.</li>
<li><strong>Blood test · 10 min</strong> Bring the form from your doctor. Some tests need you to fast the night before.</li>
<li><strong>Vaccination · 15 min</strong> Childhood vaccines, travel vaccines and the yearly flu vaccine for adults.</li>
<li><strong>Medication review · 20 min</strong> Go through your repeat medicines with a pharmacist and ask about side effects.</li>
</ul>
<a class="button" href="#">Book an appointment</a>
</main>
</body>
</html>
HTML
cat > fonts.css <<'CSS'
@font-face {
font-family: "Inter";
src: url("fonts/InterVariable.woff2") format("woff2");
font-weight: 100 900;
font-display: swap;
}
CSS
cat > style.css <<'CSS'
body {
margin: 0;
font-family: "Inter", Arial, sans-serif;
font-size: 16px;
line-height: 24px;
font-optical-sizing: none;
color: #1B1F24;
background: #F6F7F8;
}
main { max-width: 30rem; padding: 24px 16px; }
h1 { margin: 0 0 4px; font-size: 28px; line-height: 34px; font-weight: 600; }
h2 { margin: 32px 0 8px; font-size: 20px; line-height: 26px; font-weight: 600; }
p { margin: 0 0 16px; }
.muted { color: #5A6270; }
ul { margin: 0; padding: 0; list-style: none; }
li { padding: 12px 0; border-bottom: 1px solid #D5D9DF; }
strong { display: block; font-weight: 600; }
.button { display: block; margin-top: 24px; padding: 12px 16px; border-radius: 8px; background: #0F5E5A; color: #FFFFFF; font-weight: 600; text-align: center; text-decoration: none; }
CSSThe colours are Larkfield's colour/text, colour/text-muted, colour/canvas, colour/line and colour/accent, and the sizes follow its text styles: 28 for the main heading, 20 for section headings and 16 on a 24 line height for body text. font-optical-sizing: none keeps Inter on its text cut at every size, which is how Larkfield uses it, instead of letting the browser switch headings to the tighter display cut.
Check it worked
Browser developer tools only throttle real network requests, and a page opened straight from disk (a file:// address) also handles the font preload you add later differently from a real site. So serve the folder over HTTP. Open a second terminal and run this, then leave it running for the rest of the tutorial:
cd ~/font-shift-demo
npx --yes http-server@14.1.1 -p 8080 -c-1-c-1 turns off caching, so every reload fetches your latest files. Open http://localhost:8080/ in your browser and use that address for every browser check in this tutorial. The page is in Inter, and the greeting line shows ẹ and ọ with their dots below and tone marks above, all in the same typeface as the rest of the line. On your own machine the font arrives almost instantly, so you will not see it swap. The next step slows it down on purpose.
Step 3 · Measure the shift
Layout shift is easiest to see on a slow connection, which is what many of the clinic's patients have on a prepaid mobile plan. This script serves the folder to Chromium at a made-up address, holds every font file back for 1.5 seconds, and adds up the browser's own layout-shift reports while the page loads. It uses a 360 by 740 pixel viewport, a common size for budget Android phones:
cd ~/font-shift-demo
cat > measure.mjs <<'JS'
import { chromium } from 'playwright';
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { extname, join } from 'node:path';
const label = process.argv[2] ?? 'run';
const types = { '.html': 'text/html', '.css': 'text/css', '.woff2': 'font/woff2' };
const requests = [];
let fontBytes = 0;
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 360, height: 740 } });
// Serve this folder at a made-up address and hold each font back for 1.5 seconds.
await page.route('https://larkfield.test/**', async (route) => {
const path = new URL(route.request().url()).pathname;
requests.push(path);
let body;
try {
body = await readFile(join(process.cwd(), path === '/' ? 'index.html' : path));
} catch {
console.error(`Not found: ${path}`);
return route.fulfill({ status: 404 });
}
if (path.endsWith('.woff2')) {
fontBytes += body.length;
await new Promise((resolve) => setTimeout(resolve, 1500));
}
await route.fulfill({ body, contentType: types[extname(path) || '.html'] });
});
// Add up every layout shift and note the biggest vertical jump of any element.
await page.addInitScript(() => {
window.shift = 0;
window.biggestMove = 0;
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
window.shift += entry.value;
for (const source of entry.sources) {
if (!source.previousRect.height || !source.currentRect.height) continue;
const moved = Math.abs(source.currentRect.y - source.previousRect.y);
window.biggestMove = Math.max(window.biggestMove, moved);
}
}
}).observe({ type: 'layout-shift', buffered: true });
});
await page.goto('https://larkfield.test/');
await page.evaluate(async () => {
await document.fonts.ready;
await new Promise((resolve) => setTimeout(resolve, 500));
});
const { shift, biggestMove } = await page.evaluate(() => ({
shift: window.shift,
biggestMove: window.biggestMove,
}));
await browser.close();
const result = {
label,
fontBytes,
shift: Number(shift.toFixed(4)),
biggestMove: Math.round(biggestMove),
requests,
};
await mkdir('results', { recursive: true });
await writeFile(`results/${label}.json`, JSON.stringify(result, null, 2) + '\n');
console.log(result);
JS
node measure.mjs beforeshift is the sum of the layout-shift scores the browser reported, the same numbers CLS is built from. biggestMove is the largest distance, in CSS pixels, that any element jumped. requests is the order in which the browser asked for files.
Check it worked
The script prints something like this, and saves it as results/before.json:
{
label: 'before',
fontBytes: 352240,
shift: 0.02,
biggestMove: 24,
requests: [ '/', '/fonts.css', '/style.css', '/fonts/InterVariable.woff2' ]
}Your numbers may differ a little by system, but shift should be well above zero. A biggestMove of 24 is likely one line of body text: for example a paragraph that gained a line when Inter replaced Arial, which is about 7% narrower, pushing the list and button down. The font is also the last file requested, because the browser only asks for it once it has read both stylesheets and found text that uses it.
Step 4 · Subset the font and keep West African letters
The full Inter file covers more than 2,800 characters, including Greek, Cyrillic and Vietnamese. The clinic's pages need far fewer. A subset is a copy of the font with only the characters you list, and the glyphs, accents and positioning rules they need.
Be deliberate about the list. Start with basic Latin and the Latin-1 block for English and European names, then add what the clinic's languages use: Yoruba's dotted ẹ, ọ and ṣ, Hausa's hooked ɓ, ɗ, ƙ and ƴ, Igbo's ị, ụ and ṅ, and the open ɛ and ɔ used in Akan and Ewe. Yoruba tone marks are often typed as separate combining accents, so keep the combining grave, acute, macron and dot below. Add the naira and cedi signs, because prices on Nigerian and Ghanaian pages use them.
The script also shrinks the variable font's ranges. Larkfield uses only Regular (400) and Semi Bold (600), so the weight axis is limited to 400 to 600, and Inter's optical size axis is fixed at its text setting, 14. That is the same text cut that font-optical-sizing: none already asks for in style.css:
cd ~/font-shift-demo
cat > subset.mjs <<'JS'
import { readFile, writeFile } from 'node:fs/promises';
import subsetFont from 'subset-font';
const range = (from, to) =>
Array.from({ length: to - from + 1 }, (_, i) => String.fromCodePoint(from + i)).join('');
const keep = [
range(0x20, 0x7e), // basic Latin: English letters, digits, punctuation
range(0xa0, 0xff), // Latin-1: é, ü, ç, £ and the non-breaking space
'ẹẸọỌṣṢńŃǹǸḿḾ', // Yoruba
'ɓƁɗƊƙƘƴƳʼ', // Hausa
'ịỊụỤṅṄ', // Igbo
'ɛƐɔƆŋŊɖƉƒƑɣƔʋƲ', // Akan, Ewe and other Gbe languages
'̣̀́̄', // combining grave, acute, macron and dot below
'₦₵€‘’“”–—…•', // naira, cedi, euro, curly quotes, dashes
].join('');
const source = await readFile('fonts/InterVariable.woff2');
const subset = await subsetFont(source, keep, {
targetFormat: 'woff2',
variationAxes: { opsz: 14, wght: { min: 400, max: 600 } },
});
await writeFile('fonts/larkfield-inter.woff2', subset);
console.log(`${[...keep].length} characters kept`);
console.log(`Before: ${source.length} bytes. After: ${subset.length} bytes.`);
JS
node subset.mjsNow prove the subset covers real text. This script takes a font file and checks every character of a sample line against it, printing any that are missing with their Unicode code point:
cd ~/font-shift-demo
cat > coverage.mjs <<'JS'
import * as fontkit from 'fontkit';
const file = process.argv[2];
const sample = 'Ẹ káàbọ̀ · Barka da zuwa · Nnọọ · Ɓ ɓ Ɗ ɗ Ƙ ƙ Ƴ ƴ · ị ụ ṅ · Ɛ ɛ Ɔ ɔ Ŋ ŋ · ₦5,000 · ₵20';
const font = fontkit.openSync(file);
const missing = [...new Set(sample.replace(/\s/g, ''))]
.filter((char) => !font.hasGlyphForCodePoint(char.codePointAt(0)))
.map((char) => `U+${char.codePointAt(0).toString(16).toUpperCase().padStart(4, '0')}`);
console.log(missing.length ? `${file} is missing ${missing.join(' ')}` : `${file} covers the sample`);
JS
node coverage.mjs fonts/larkfield-inter.woff2
node coverage.mjs node_modules/inter-ui/variable-latin/InterVariable-subset.woff2The second line checks the ready-made Latin subset that ships in the same package, for comparison.
Check it worked
subset.mjs reports about 250 characters kept and a file of roughly 50 KB, down from 352 KB. The first coverage check prints fonts/larkfield-inter.woff2 covers the sample. The second prints a list of missing code points that includes U+1EB8 (Ẹ), U+0253 (ɓ) and U+20A6 (₦). That is what a page in Yoruba or Hausa would have lost with a generic Latin subset.
The script checks each code point on its own, so the ọ̀ in the greeting is checked as ọ followed by a combining grave accent, which is how it is often typed. When you add a language, add a real sentence from it to sample, preferably from a native speaker or your own translated content, and run the check again.
Step 5 · Point the page at the subset and preload it
Replace the @font-face rule so it serves the subset and declares the weight range the file now holds:
cd ~/font-shift-demo
cat > fonts.css <<'CSS'
@font-face {
font-family: "Inter";
src: url("fonts/larkfield-inter.woff2") format("woff2");
font-weight: 400 600;
font-display: swap;
}
CSSNext, tell the browser about the file before it reads any CSS. A preload link in the <head> starts the download while the HTML is still being parsed, instead of after both stylesheets have arrived. Rewrite the head of index.html with the preload line added, keeping the body as it was:
cd ~/font-shift-demo
node -e "
const fs = require('node:fs');
const html = fs.readFileSync('index.html', 'utf8');
const head = ' <link rel=\"preload\" href=\"fonts/larkfield-inter.woff2\" as=\"font\" type=\"font/woff2\" crossorigin>\n';
if (!html.includes('rel=\"preload\"')) fs.writeFileSync('index.html', html.replace(' <link rel=\"stylesheet\" href=\"fonts.css\">', head + ' <link rel=\"stylesheet\" href=\"fonts.css\">'));
"
grep -n 'link' index.htmlIf you prefer, open index.html in your editor and add the line by hand, directly above the fonts.css link:
<link rel="preload" href="fonts/larkfield-inter.woff2" as="font" type="font/woff2" crossorigin>Each attribute earns its place. as="font" gives the request the right priority and lets the browser match it to the later @font-face request. type lets a browser that cannot use WOFF2 skip the download. crossorigin is required even on your own domain, because fonts are always fetched in CORS mode, and a preload without it is downloaded twice. Preload only the one file every page needs. Each preload competes with your HTML, CSS and main image for the same connection, which matters most on a slow 3G or 4G link.
Check it worked
grep lists the preload link on the line before the fonts.css stylesheet link. In your browser, open the developer tools on http://localhost:8080/, go to the Network panel and reload: larkfield-inter.woff2 appears once, near the top, and InterVariable.woff2 is no longer requested.
Step 6 · Choose a font-display value
font-display decides what the browser shows while the font is on its way. There are four useful values:
blockhides the text for up to about three seconds, then shows the fallback. Visitors on a slow connection stare at a blank page.swapshows the fallback at once and switches to the web font whenever it arrives, however late.fallbackhides text for about 100 milliseconds, then shows the fallback, and only switches if the font arrives within about three seconds.optionalgives the font about 100 milliseconds. If it is not ready, this page view keeps the fallback, and the browser may use the font from its cache on the next page.
Larkfield keeps swap. The text is readable from the first paint, which matters on a phone where the font can take seconds, and the brand typeface still appears. The cost of swap is the late redraw you measured, and the next step removes most of it. If a page is mostly long reading and your audience pays for every megabyte, optional is a strong choice: nobody sees a swap, and on a slow first visit the text stays in a well-tuned fallback.
Check it worked
fonts.css contains font-display: swap; and you can name the value you would use for a text-heavy page on a slow network, and why. For a live view, open http://localhost:8080/, then the Network panel, choose a slow preset from the throttling menu, disable the cache and reload. Text appears in the fallback first, then changes to Inter.
Step 7 · Tune the fallback with size-adjust
Arial's letters are narrower than Inter's, so the same sentence takes fewer words per line. You can fix that without touching Arial itself: declare a new font family that uses the local Arial file, scaled and with adjusted vertical measurements, and list it straight after Inter.
Four descriptors do the work:
size-adjustscales every glyph. Set it to the ratio of the average letter widths of the two fonts, so a line of the fallback is about as long as the same line in Inter.ascent-overrideanddescent-overrideset how far the font reaches above and below the baseline. Use Inter's values, divided bysize-adjustbecause the browser applies the scale to them too.line-gap-overridesets the extra space between lines. Inter has none, so it is 0.
The script reads Inter's measurements from your subset file, takes Arial's and Roboto's from the Capsize metrics package, and writes the rules to fallback.css. Roboto gets its own family because it is the system font on most Android phones, which have no Arial:
cd ~/font-shift-demo
cat > fallback.mjs <<'JS'
import { writeFile } from 'node:fs/promises';
import { fromFile } from '@capsizecss/unpack/fs';
import arial from '@capsizecss/metrics/arial';
import roboto from '@capsizecss/metrics/roboto';
const web = await fromFile('fonts/larkfield-inter.woff2');
const percent = (value) => `${(value * 100).toFixed(2)}%`;
function fallbackFace(name, localNames, local) {
// How much wider the web font's average letter is than the local font's.
const sizeAdjust = web.xWidthAvg / web.unitsPerEm / (local.xWidthAvg / local.unitsPerEm);
return `@font-face {
font-family: "${name}";
src: ${localNames.map((n) => `local("${n}")`).join(', ')};
size-adjust: ${percent(sizeAdjust)};
ascent-override: ${percent(web.ascent / web.unitsPerEm / sizeAdjust)};
descent-override: ${percent(Math.abs(web.descent) / web.unitsPerEm / sizeAdjust)};
line-gap-override: ${percent(web.lineGap / web.unitsPerEm / sizeAdjust)};
}
`;
}
const css = [
fallbackFace('Inter fallback', ['Arial', 'ArialMT', 'Liberation Sans', 'LiberationSans'], arial),
fallbackFace('Inter fallback Android', ['Roboto', 'Roboto-Regular'], roboto),
].join('\n');
await writeFile('fallback.css', css);
console.log(css);
JS
node fallback.mjs
cat fallback.css >> fonts.csslocal() names a font installed on the visitor's device, so nothing extra downloads. Liberation Sans, found on many Linux systems, has the same letter widths as Arial, so it shares Arial's numbers. If none of a family's local fonts exist on the device, the browser skips that family and tries the next one in the list.
Now put the two fallback families into the font stack, between Inter and the plain fallbacks:
cd ~/font-shift-demo
cat >> style.css <<'CSS'
body {
font-family: "Inter", "Inter fallback", "Inter fallback Android", Arial, sans-serif;
}
CSS
node measure.mjs afterThe new body rule comes later in the file, so its font-family replaces the earlier one. Tidy the first rule by hand when you are done.
Check it worked
fallback.mjs prints two @font-face rules. The Arial one has a size-adjust of about 107%, which matches the roughly 7% difference that made lines wrap earlier. The measurement prints something like this:
{
label: 'after',
fontBytes: 50924,
shift: 0,
biggestMove: 0,
requests: [ '/', '/fonts/larkfield-inter.woff2', '/fonts.css', '/style.css' ]
}The font is now about a seventh of its old size, it is requested straight after the HTML, and the layout shift is close to zero even though the font still arrives 1.5 seconds late. Compare results/before.json and results/after.json side by side.
Troubleshooting
If shift is still well above zero, look for a line that sits right at the edge of its box. size-adjust matches the average letter width, not every word, so a line that only just fits can still wrap differently. The greeting line on this page was kept short for that reason. Bold text is scaled from the regular fallback with a synthetic bold, so long passages of bold text may need their own fallback face with font-weight: 600 and a local bold font. If fontBytes is unchanged, the browser is still loading the old file: check the src in fonts.css.
Step 8 · Check the result on a real page and device
The script is a controlled test. Check the page in the browser at http://localhost:8080/, where real network timing and real fallback fonts apply:
- In Chrome or Edge, open the developer tools, then the Rendering panel from the three-dot menu under More tools, and tick Layout Shift Regions. Reload with a slow throttling preset and the cache disabled. Areas that move flash blue, so a well-tuned page shows little or no flashing when the font swaps.
- Record a reload in the Performance panel and look for layout shift markers around the time the font finishes downloading.
- Open the page on an Android phone, where the fallback is Roboto rather than Arial. On the same Wi-Fi network, use your computer's local IP address instead of
localhost, for example http://192.168.1.20:8080/ (http-serverprints the addresses it listens on). If text jumps there, check that"Inter fallback Android"is in the font stack. Android versions differ in how they name their system fonts, so test on the phones your visitors use.
Check it worked
With Layout Shift Regions on and a slow preset, http://localhost:8080/ shows text in the fallback first, then Inter, with the list and button staying where they were. On a phone, the greeting line shows ẹ, ọ and the tone marks in the same typeface as the words around them.
Step 9 · Clean up
Stop the server in the second terminal with Ctrl+C. Then remove the demo folder. If you installed Playwright's browser only for this tutorial, remove its download too, which is shared between projects and lives in Playwright's cache folder (~/.cache/ms-playwright on Linux, ~/Library/Caches/ms-playwright on macOS):
cd ~
rm -rf ~/font-shift-demoNext steps
- Pick the typeface in the first place, with language coverage and file size as tests: choose and pair typefaces for an interface.
- A web font is often part of the largest element on the screen. Improve Largest Contentful Paint shows how to find what delays it.
- Put the whole page on a data budget: test and speed up a page on a slow phone connection.
- Make the Larkfield type scale fluid between phone and desktop: build fluid type with CSS clamp().
Related tutorials
- Organise CSS with cascade layersYou will have a stylesheet for the Larkfield Clinic booking app split into reset, tokens, base, vendor, layout, components and utilities layers, a third-party widget that can no longer override your components, no !important left, and a Playwright script that checks the computed styles.
- Make components work in forced colours modeYou will find the Larkfield Clinic components that lose their meaning when Windows forced colours replace the page palette, fix them with a transparent border, currentColor and system colour keywords inside a forced-colors media query, and keep them fixed with a Playwright test that runs under emulation.
- Build a living style guide page from CSS tokensYou will have a style guide page that reads every token from tokens.css when it loads and shows the palette with contrast ratios, the type scale, the spacing scale and the Larkfield components in their states, plus a Playwright test that fails when a token is missing.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials