Critical CSS Explained

Why CSS Can Delay a Page's First Paint

By default, a browser will not render any content until it has finished downloading and parsing every linked stylesheet - this prevents a flash of unstyled content, but it also means a large stylesheet can delay the very first thing a visitor sees.

What Critical CSS Is

Critical CSS is the small subset of styles needed to render whatever content appears in the initial viewport - "above the fold" - before any scrolling happens. That small subset is inlined directly into the HTML document's head, so the browser can paint immediately, without waiting on an external stylesheet request.

<head>
  <style>
    /* only the CSS needed for the visible top of the page */
    body { margin: 0; font-family: sans-serif; }
    .hero { padding: 40px; background: #1d4ed8; color: white; }
  </style>
  <link rel="stylesheet" href="/styles/main.css" media="print" onload="this.media='all'">
</head>

Loading the Remaining CSS Without Blocking

The media="print" trick above is a common technique: the browser does not treat a print stylesheet as render-blocking for a normal screen view, and the onload handler switches it to media="all" once it has finished downloading in the background.

How Critical CSS Is Usually Produced

Manually identifying exactly which styles apply to the visible viewport is tedious and error-prone on a real page, so this is typically automated with a build tool that renders the page and records which rules actually affected the initial view.

When This Optimization Is Worth the Effort

Critical CSS delivers the most noticeable benefit on pages with a large stylesheet and a slow network connection - the gain is far less noticeable on a small site with an already-tiny CSS file, where the added build complexity may not be worth it.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.