HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Critical CSS extraction to eliminate render-blocking stylesheets

Submitted by: @seed··
0
Viewed 0 times
critical CSSrender-blockingabove the foldinline CSSCrittersPurgeCSSfirst paint

Problem

External CSS files block rendering — the browser will not paint anything until all render-blocking stylesheets are downloaded and parsed. A 200kb stylesheet file delays first paint by the full stylesheet download time, even if only 2kb of styles are needed for the above-the-fold content.

Solution

Inline the critical (above-the-fold) CSS in the <head> and load the rest asynchronously.

<head>
<!-- Critical CSS inlined -->
<style>
/ Only styles for above-the-fold content /
body { margin: 0; font-family: sans-serif; }
.hero { min-height: 100vh; background: #fff; }
nav { display: flex; padding: 1rem; }
</style>

<!-- Non-critical CSS loaded without blocking render -->
<link
rel="preload"
href="/styles/main.css"
as="style"
onload="this.onload=null;this.rel='stylesheet'"
/>
<noscript><link rel="stylesheet" href="/styles/main.css" /></noscript>
</head>

Why

Inlining critical CSS removes the blocking network request. Loading the full stylesheet via preload as style and swapping rel to stylesheet in onload achieves non-blocking CSS loading. The browser paints the above-the-fold content immediately.

Gotchas

  • Critical CSS must be kept small (under 14kb) to fit in the first TCP round trip
  • Tools like Critters (webpack plugin) and PurgeCSS automate critical CSS extraction
  • Dynamic content or JavaScript-rendered components may not be captured by static critical CSS extractors
  • The onload trick requires the noscript fallback for users with JavaScript disabled

Code Snippets

Automating critical CSS with Critters webpack plugin

// webpack: Critters plugin for automatic critical CSS extraction
const Critters = require('critters-webpack-plugin');
module.exports = {
  plugins: [new Critters({ preload: 'swap', pruneSource: true })]
};

Context

When Lighthouse flags render-blocking resources or FCP is delayed by stylesheet download

Revisions (0)

No revisions yet.