DEV Community

Melisa Wong
Melisa Wong

Posted on

My static site ships the same stylesheet 290 times. Inline CSS is why none of it can be cached.

I generate a static site from a build script: a few hundred pages, one template, per-page text, and one inline <style> block in every <head>. That last part is a caching decision I never consciously made. I just never removed the block.

Last week I ran three measurements on the output directory: how much of the CSS is duplicated, how much of each block is unreferenced on the page that ships it, and what a multi-page visit actually transfers. Only the third one changed my mind. The first two are the reason I could not see the problem.

1. The duplication factor

The audit is about thirty lines. Walk the HTML files, pull out every <style> block, hash it, group pages by hash, then divide total CSS bytes by the bytes of one page per group.

const blocks = new Map();
for (const f of files) {
  const html = fs.readFileSync(f, 'utf8');
  const css = [...html.matchAll(/<style[^>]*>([\s\S]*?)<\/style>/gi)]
    .map(m => m[1]).join('\n');
  const key = sha256(css).slice(0, 12);
  if (!blocks.has(key)) blocks.set(key, { css, pages: [] });
  blocks.get(key).pages.push(f);
}

const total  = files.reduce((a, f) => a + cssBytesOf(f), 0);
const unique = [...blocks.values()].reduce((a, b) => a + Buffer.byteLength(b.css), 0);
const factor = total / unique;
Enter fullscreen mode Exit fullscreen mode

Output on 290 pages:

metric value
pages 290
distinct <style> blocks 16
inline CSS, raw 1,931,855 B
inline CSS, distinct only 108,072 B
duplication factor 17.88×

Same numbers after gzip: 568,011 B versus 31,007 B of distinct CSS, so 18.3×. Compression does not touch this, because gzip has no memory between documents. Each page compresses its own copy of the same bytes, from scratch, forever.

I expected two or three duplicates from stale build snapshots. Sixteen distinct blocks means the template forked sixteen ways, and every page kept the fork it was born with.

2. Where sixteen came from

I diffed each block against the largest one (70 pages, 6,336 B, 66 rules), comparing rule sets:

pages bytes rules rules added vs base rules removed Jaccard
70 6,336 66 0 0 1.000
56 6,633 70 +4 0 0.943
50 6,791 69 +3 0 0.957
46 6,527 66 +3 −3 0.913
20 9,052 91 +25 0 0.725
12 6,634 70 +4 0 0.943
9 6,072 63 0 −3 0.955
8 7,563 77 +11 0 0.857
11 4,345 47 0 −19 0.712

243 of the 290 pages (83.8%) ship a block that is at least 91% identical to the biggest one. Four of the blocks are strict supersets — rules added, none removed. That is the signature of a build that appends instead of edits.

Two concrete cases:

  • .lang-bar, 4 rules for the language switcher. Those rules ship inside 64 pages that do not contain the element at all — 56 pages in one group, 8 in another. The pages that do contain it are a small locale-index set.
  • .ns-answer, 3 rules for an answer-first block. It ships in 50 pages; 10 of them have no such block in the markup.

The mechanism is boring and I think common: the generator writes the template for the page type it is currently emitting, appends the feature CSS for that page type, and never looks at what the other page types already have. Each page is a snapshot from the day it was generated. Nothing removes anything, ever. Sixteen snapshots later, you have sixteen stylesheets and no single place to change a color.

3. How much of each block is dead

Second measurement: for each page, collect every class and id token that appears in the markup, then check each CSS rule whose selector contains a class or id. If none of its classes or ids appear on the page, count the rule as unreferenced.

metric value
median unreferenced rules per page 26.8%
worst page 41.2%
best page 0%
median unreferenced bytes per page 1,475 B
site-wide unreferenced bytes 374,505 B

Read that as an upper bound, not a truth. It is a string-level check: :hover states, classes toggled by inline script, and selectors that legitimately match nothing all land in the "dead" bucket. The real number is lower. But the direction is consistent with section 2 — the blocks carry components their pages do not use.

And it tells me the fix cannot be "trim the shared file down to what is used", because what is used differs per page type. Trimming has to be per template.

4. The number that actually decided it

Bytes were never convincing. 1.9 KB of gzip per page is nothing. So I modelled a visit instead: take five real pages from the dominant group, sum the gzipped transfer with inline CSS, then sum it again assuming one shared, immutable, hashed stylesheet that the browser fetches once and reuses.

visit inline (current) one shared file delta
entry page 8,594 B 12,758 B +48.5%
5 pages 41,110 B 33,598 B −18.3%
20 pages 125,117 B 91,488 B −26.9%

The entry page gets worse, because the merged file is 6,042 B gzipped against the 1,878 B those pages pay today. Break-even is the third page.

But the transfer table is not the argument either. The argument is that the HTML is re-fetched on every visit, and inline CSS rides inside it. A returning visitor pays for the CSS again, in full, and there is nothing to revalidate — no URL, no ETag, no 304, no cache entry. An external hashed file gives page two of a visit 0 CSS bytes and a repeat visitor 0 bytes as well. What inline CSS buys is one round trip, once. What it costs is every round trip after that.

That is what the 1.9 KB was hiding: not the size, the impossibility.

5. What I am shipping, and the part I am unsure about

Merging all sixteen blocks and deduplicating line by line gives 409 unique rules and declarations, 25,041 B raw, 6,042 B gzipped. One file covering all 290 pages, against 568,011 B gzipped of repetition today.

option first paint repeat visits work
A. keep inline (today) fastest 0% cached none
B. one hashed <link> +1 RTT, +4,164 B on entry fully cached, 0 B extract at build, touch every template
C. critical inline + async full file fastest cached after first paint needs a real critical-path split per template

I am going with B. The cost is honest: entry gets slower by about 4 KB and one round trip, and it only pays back if people read more than two pages. For a site whose whole purpose is internal links between pages, that is a bet I am willing to make.

The thing I am not sure about is C. I have seen critical-CSS pipelines that start at 2 KB and quietly grow to 20 KB, because "critical" is decided per template and templates drift — which is exactly how I ended up with sixteen inline blocks. If you have shipped C and kept the critical set small, I want to know what stopped it from growing.

Also honest: the merged file still contains rules no page uses, like those 4 .lang-bar rules. A real trim needs a usage pass, and that pass has to run per template, not once.

One page of context

I should say what this static site is for. I build NameSoul, which gives you a Chinese name rooted in real history. You choose one of six styles — poetic, bold, five-element, nature, phonetic transliteration, or rustic folk. You see the name in brush calligraphy and in seal script, the ancient script that sits close to oracle-bone carving and that people tell me they would get tattooed. Behind it comes a past life from one of China's dynasties with the story of who you were, the real cities, landscapes and historic sites that life touched, a guardian beast from Chinese mythology, and a daily fortune.

It runs in ten languages. That is why the build has this many template variants in the first place — and, I now think, exactly why the divergent CSS blocks accumulated. Every locale added a page shape, every page shape appended a block, nobody subtracted.

Three questions

  1. B or C? If you went with critical inline plus an async stylesheet, did the critical set stay small, or did it grow back into the same duplication problem in a new file?
  2. If you tried the product: what would make you close it in the first ten seconds? That answer is worth more to me than a compliment.
  3. If there were a v1.2: what is the one thing you would add?

I am reasonably good at building the thing. I am much worse at knowing which part of it is load-bearing for someone else. That is the part I am asking about.

Top comments (0)