Two Times Inlining CSS Made FCP Slower, and How I Now Decide Per Site Whether to Inline
I inlined CSS into the HTML to clear PageSpeed Insights' render-blocking warning, and FCP got almost a second slower. The font preload had been pushed down to byte 28,672 of the head. Even after fixing the placement, the same change made a second site with 88KB of CSS slower, and I rolled it back. Here is a script that counts byte offsets inside the head, an inliner with a size cap, and the pattern I use on the larger site instead.
I was running an artist's official site through PageSpeed Insights (PSI) when the "Eliminate render-blocking resources" item showed exactly one entry: the CSS file Next.js had written out. 7.3 KiB, with an estimated saving of 1,260 ms. The site had only a few pages and about 19KB of CSS in total.
Put it all in a <style> tag and that entry disappears — that was my reasoning. I added a small script after the build and measured again. The warning was gone. First Contentful Paint, though, was almost a second slower.
As an indie developer who builds and runs his own sites, I find there is a particular satisfaction in clearing PSI warnings one by one, and it is easy to stop at the screen where the warning vanished. What follows is what caused that delay, the second time I tripped on the same change on a different site, and how I decide now.
The answer first
Inlining CSS can help or hurt depending on two things: where you put it and how big it is.
Placement: if you drop the CSS where the original <link rel="stylesheet"> was, the font <link rel="preload"> behind it gets pushed down, and the browser finds the font later. Putting the <style> right before </head> avoids that.
Size: on a site with a lot of CSS, the HTML itself gets heavy and FCP got worse even with correct placement. In my notes, it helped on a 19KB site and I rolled it back on an 88KB site.
Neither shows up directly on the PSI screen. The quickest way to see it is to open the built HTML and count the head byte by byte.
First mistake: the font preload sank to byte 28,672
My first script was naive. It looked for <link> tags pointing at /_next/static/css/… in every HTML file under out/, and replaced each one in place with the CSS contents. A single replace — the shortest thing you can write.
Each page grew by 26KB (6KB after gzip). In exchange one CSS request went away, so total transfer was about the same. On paper it should have been faster.
The reason it wasn't was the order of things in the head. In the Next.js export, the CSS <link> comes before the font preload. Dropping 26KB of CSS into that spot pushed the preload back.
How the CSS was inserted
Byte offset of the font preload
At the original <link> position
byte 28,672
Right before </head>
byte 1,276
Browsers scan ahead in the HTML to start fetching images and fonts early (the preload scanner). If the preload sits 28KB in, it is discovered later. The heavier the font — Japanese faces especially — the more directly that delay lands on FCP.
Because the render-blocking warning was gone, the PSI screen looked like an improvement. The built HTML was the last place I looked when I went hunting for why the number had gone the wrong way.
✦
Thank you for reading this far.
Continue Reading
What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.
WHAT YOU'LL LEARN
✦When FCP gets worse after inlining CSS, you can count the byte offset of the font preload in the head and tell within minutes whether placement is the cause
✦You can add a build step that measures total CSS before inlining and skips pages over a cap, stopping a change that backfires on large sites before it ships
✦You will know how many PSI runs to take and what to compare when the numbers wobble from run to run, so you can decide whether to roll back
Secure payment via Stripe · Cancel anytime
✦
Unlock This Article
Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.
Back then I was checking the byte offset of the font filename with grep -bo, one file at a time. Now I use the script below so every page is listed on every build. I checked it against sample HTML: the page with the pushed-down preload comes out NG and the correct one comes out ok.
// head-order.mjs// For each HTML file under out/, list the byte offsets of key tags inside <head>.// Usage: node head-order.mjs [out] [allowed bytes]import fs from 'node:fs';import path from 'node:path';const OUT = process.argv[2] ?? 'out';const LIMIT = Number(process.argv[3] ?? 4096); // the font preload should appear within this many bytesfunction walk(dir) { return fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => { const p = path.join(dir, e.name); return e.isDirectory() ? walk(p) : e.name.endsWith('.html') ? [p] : []; });}// Count bytes, not characters (they differ a lot on pages with Japanese text)const byteAt = (html, idx) => (idx < 0 ? -1 : Buffer.byteLength(html.slice(0, idx)));let bad = 0;for (const file of walk(OUT)) { const html = fs.readFileSync(file, 'utf8'); const headEnd = html.indexOf('</head>'); const head = headEnd < 0 ? html : html.slice(0, headEnd); const font = byteAt(head, head.search(/<link[^>]+rel="preload"[^>]+as="font"/)); const style = byteAt(head, head.indexOf('<style')); const sheet = byteAt(head, head.search(/<link[^>]+rel="stylesheet"/)); const imgPreloads = [...head.matchAll(/<link[^>]+rel="preload"[^>]+as="image"[^>]*>/g)]; const imgBeforeFont = imgPreloads.filter((m) => font >= 0 && byteAt(head, m.index) < font).length; const problems = []; if (font < 0) problems.push('no font preload'); else if (font > LIMIT) problems.push(`font preload at byte ${font}`); if (style >= 0 && font >= 0 && style < font) problems.push('<style> comes before the font preload'); if (imgBeforeFont > 0) problems.push(`${imgBeforeFont} image preload(s) before the font`); console.log( `${problems.length ? 'NG' : 'ok'} ${file} font=${font} style=${style} stylesheet=${sheet} ` + `img-preload=${imgPreloads.length} head=${byteAt(html, headEnd)}B` + (problems.length ? `\n -> ${problems.join(' / ')}` : '') ); if (problems.length) bad++;}process.exit(bad ? 1 : 0);
It looks at three things: how far the font preload is from the top, whether a <style> comes before it, and whether any image preload has jumped ahead of the font.
The third check is there for a reason. On the same site, I had set images with srcset to loading="eager", and React automatically injected <link rel="preload" as="image"> at the top of the head. The four slideshow images I was prefetching ended up ahead of the font, and FCP on a slow connection went from 2.7 s to 3.7 s. Limiting eager to the single image needed for the first view fixed it. I wrote about another srcset trap in the post on how a too-small sizes value shrinks the image itself.
The 4096-byte allowance is a rough line I set with some margin above the 1,276 bytes the font preload sat at once fixed. Your head will differ, so I'd look at a correctly ordered page first and set it from there.
Inlining with a cap
After moving the <style> to just before </head>, I added one more line to the inliner itself: if a page's CSS adds up to more than a cap, it is left alone and the script says why. I added it because of the mistake in the next section.
// inline-css-guarded.mjs// After next build, inline the CSS each page loads into a <style> tag.// Pages whose CSS total exceeds the cap are left as-is, with a log line saying why.import fs from 'node:fs';import path from 'node:path';const OUT = 'out';const MAX_INLINE = Number(process.env.MAX_INLINE_CSS ?? 24 * 1024); // cap on inlined CSS per page (bytes)const LINK_RE = /<link[^>]+rel="stylesheet"[^>]*href="(\/_next\/static\/css\/[^"]+\.css)"[^>]*\/?>/g;function walk(dir) { return fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => { const p = path.join(dir, e.name); return e.isDirectory() ? walk(p) : e.name.endsWith('.html') ? [p] : []; });}const cssCache = new Map();const readCss = (href) => { const p = path.join(OUT, href); if (!fs.existsSync(p)) return null; // leave the link in place if the CSS is missing if (!cssCache.has(p)) cssCache.set(p, fs.readFileSync(p, 'utf8')); return cssCache.get(p);};let inlined = 0, skipped = 0;for (const file of walk(OUT)) { const html = fs.readFileSync(file, 'utf8'); const hrefs = [...html.matchAll(LINK_RE)].map((m) => m[1]); if (hrefs.length === 0) continue; // already inlined: running it twice gives the same result const bodies = hrefs.map(readCss); if (bodies.includes(null)) { console.warn(`skip (CSS not found): ${file}`); skipped++; continue; } const total = bodies.reduce((n, css) => n + Buffer.byteLength(css), 0); if (total > MAX_INLINE) { console.warn(`skip (${(total / 1024).toFixed(1)} KB > cap): ${file}`); skipped++; continue; } // Remove the links and put a single <style> right before </head>. // Inserting at the original link position pushes the font preload behind it. const css = bodies.join('\n').replace(/<\/style/gi, '<\\/style'); const out = html.replace(LINK_RE, '').replace('</head>', `<style>${css}</style></head>`); fs.writeFileSync(file, out); inlined++;}console.log(`inlined=${inlined} skipped=${skipped} (cap ${MAX_INLINE} bytes)`);
In package.json I chain it as "build": "next build && node scripts/inline-css-guarded.mjs && node scripts/head-order.mjs out", so the whole build stops if the order breaks. I checked three behaviours against sample HTML: inlining, a no-op second run, and skipping a page over the cap.
The 24KB cap is just my own line, placed between the site where it helped (19KB) and the one where it hurt (88KB). I didn't measure where the boundary actually is, so please compare before and after on your own site, as in the section on measuring below, before moving it.
Second mistake: correct placement, still slower at 88KB
With placement fixed, the script worked, so I put the same thing into another artist's site with a much larger body of work. That site's CSS is 88KB.
It went the other way. Before the change, FCP wobbled between 3.2 and 3.8 s depending on the run. After inlining, it was 4.3 s. That was outside the wobble, so I rolled it back.
The reason I wrote down was that the HTML gets heavier and everything after the first byte is delayed. With CSS as a separate file, the browser can fetch it in parallel while it receives the HTML. Inline it, and those 88KB arrive as part of the HTML, so rendering the body starts later.
Looking back, the real problem was that I carried the script over simply because it had worked once. A change that worked only travels well if you carry the conditions it worked under along with it; on another site it is a different change.
What I use on the larger site instead
The 88KB site does not inline everything today. Only the top page inlines the 1.4KB of CSS the opening sequence needs, and the main stylesheet is loaded in a way that doesn't block rendering.
<head> <!-- Only what the first screen needs (1.4KB on this site) --> <style>/* positioning for the opening curtain and the poster image only */</style> <!-- Load the main CSS without blocking rendering; switch to all once loaded --> <link rel="stylesheet" href="/_next/static/css/app.css" media="print" onload="this.media='all'"> <noscript><link rel="stylesheet" href="/_next/static/css/app.css"></noscript></head>
Until the main CSS arrives, everything except the curtain and the poster stays hidden. Otherwise a broken layout flashes for a moment.
There was a trap here too. Instead of media="print", many guides suggest prefetching with <link rel="preload" as="style">. On this site React re-inserted the link and rendering stalled, so I settled on switching media. With Next.js and React, code that rewrites the built HTML and the client-side code that manages the head can collide; it's worth keeping that in mind.
Hiding content like this also doesn't get along with code that measures element positions right after load. Measure before layout settles and you get the wrong numbers, so on this site I added re-measurement after load. If you change how CSS arrives, look for anything that measures exactly once on mount.
How I measure before deciding to roll back
The lesson from the second mistake was that one run isn't enough. The "before" numbers alone moved by about 0.6 s, so comparing one run against one run could be read as either better or worse.
Now I run PSI mobile on the same URL several times and compare the median along with the min and max. The API part looks like this.
#!/usr/bin/env bash# psi-fcp.sh — run PSI (mobile) N times on one URL and print FCP median and range.# Usage: PSI_KEY=... bash psi-fcp.sh https://example.com/ 5set -euo pipefailURL="$1"; N="${2:-5}"API="https://www.googleapis.com/pagespeedonline/v5/runPagespeed"vals=()for i in $(seq 1 "$N"); do v=$(curl -s --get "$API" --data-urlencode "url=$URL" -d strategy=mobile -d category=performance \ ${PSI_KEY:+-d key="$PSI_KEY"} \ | jq -r '.lighthouseResult.audits["first-contentful-paint"].numericValue // empty') [ -n "$v" ] || { echo "run $i: failed (check quota or URL)" >&2; continue; } printf 'run %d: FCP %.0f ms\n' "$i" "$v" vals+=("$v") sleep 20 # space the runs out to catch network and server variationdone[ "${#vals[@]}" -gt 0 ] || exit 1printf '%s\n' "${vals[@]}" | sort -n | awk '{a[NR]=$1} END{m=(NR%2)?a[(NR+1)/2]:(a[NR/2]+a[NR/2+1])/2; printf "median: %.0f ms (n=%d, min %.0f / max %.0f)\n", m, NR, a[1], a[NR]}'
You can call it without an API key, but the shared quota runs out quickly and you may get a 429 (daily limit exceeded). If you plan to measure repeatedly, create a key in Google Cloud and pass it as PSI_KEY.
My rule of thumb is simple. If the best "after" run is worse than the worst "before" run, roll back. While the ranges overlap, don't decide yet. On the 88KB site the worst "before" was 3.8 s and "after" was 4.3 s, so the call was easy.
Pitfalls
Don't treat a cleared PSI warning as success. The render-blocking item can disappear while FCP gets worse. Decide on FCP before and after, not on whether the warning is there.
Count bytes, not characters. On pages with a lot of Japanese, indexOf positions and byte positions drift far apart. The preload scanner reads bytes, so the script above uses Buffer.byteLength.
Don't inline CSS containing </style> as-is. If a string inside the CSS contains </style, the style element ends right there. Escape it before inlining.
Keep the CSS files. Other pages or old caches may still reference them after inlining. My script leaves the original files untouched.
Check English and Japanese pages separately. Font preloads and CSS volume can differ by language. Running the order check over every page is the safe way.
What I hand over when an agent does this
If you only say "inline the CSS and clear the PSI warning," it wouldn't be surprising for the shortest replace — inserting at the original position — to be chosen. That's exactly what I wrote first. If I hand this to an Antigravity agent, I think it's safer to spell out three things in the request.
For out/**/*.html after the build, replace <link rel="stylesheet"> tags under /_next/static/css with <style>.- Put a single <style> right before </head> (not where the link was)- If a page's CSS totals more than 24KB, don't inline it; log it and leave the page alone- When done, run node scripts/head-order.mjs out and show in the output that every page is okI'll re-run PSI myself. Please don't judge whether the numbers are better or worse.
The last line is there because I want measuring and judging kept apart. Ask the agent to decide whether it got faster, and the conclusion comes from a single run. The hands-on work and the order check go to the agent; running PSI several times and deciding whether to roll back stays with me. Split that way, I think a mistake like the second one is less likely to ship on the strength of "it should have helped."
Speed work looked like applying an answer someone had already written down. In practice it was rechecking my own site's conditions one at a time. The same warning on a 19KB site and an 88KB site turned out to be two different problems.
Where I draw the line
Whether to inline is decided per site, after looking at the CSS size and the order of the head. I don't carry the script from a site where it worked straight into the one next door; that's the line I keep now.
As a first step, I'd run head-order.mjs once over your current build and see which byte the font preload sits at. Even on a site that doesn't inline anything, you might notice an image preload overtaking the font.
Share
Thank You for Reading
Antigravity Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.