Inline Critical CSS
A <link rel="stylesheet"> in the head blocks rendering until it downloads. Inlining the rules the first viewport needs lets the browser paint before the full stylesheet arrives.
Procedure
Measure the blocking cost first, from a throttled run's render-blocking-resources audit:
npx lighthouse https://shop.example.com --only-audits=render-blocking-resources --output=json | jq '.audits."render-blocking-resources".details.items'Extract the critical rules at the exact viewport you care about (mobile is the default target):
npx critical https://shop.example.com/ --base dist --inline --width 1300 --height 900 \ --minify true --extract false > dist/tmp.htmlInline the result in a
<style>block in the head, and load the full sheet asynchronously with the preload/onload trick ormedia="print":<link rel="stylesheet" href="/app.css" media="print" <noscript><link rel="stylesheet" href="/app.css"></noscript>Purge rules that no route uses so the deferred sheet shrinks too:
npx purgecss --css dist/app.css --content 'src/**/*.tsx' --output dist/Re-run the audit; the page should no longer list a render-blocking CSS resource in the first viewport.
Regenerate the critical CSS on every route/design change, wired into the build, or it silently drifts.
Pitfalls
- Inlining the whole stylesheet, which bloats every HTML response and delays the very paint you were optimizing.
- Generating critical CSS at one viewport and shipping it to all; a wide desktop layout then flashes unstyled content.
- Forgetting the
<noscript>fallback, leaving the page unstyled without JS. - Building critical CSS by hand and letting it rot; it must be regenerated by the build.
- Loading the deferred sheet with
asyncon a<link>, which is invalid and silently does nothing.
Verification
curl -s https://shop.example.com/ | grep -c 'rel="stylesheet"'
The head must contain an inline <style> and, at most, one deferred stylesheet link with a noscript fallback. Report the count and the delta in the render-blocking audit.