Sub topic 11
Performance: Render Blocking and Caching
This chapter covers how each way of attaching CSS affects page load speed. It assumes you can write all three methods (the style attribute, the style element, and <link rel="stylesheet">) and know the basics of HTTP requests and responses. You do not need to know server configuration. The header examples are short and explained as they appear.
Why CSS affects load speed
A browser builds two structures before it can draw a page. The DOM is the tree of elements parsed from the HTML. The CSSOM is the tree of style rules parsed from all the CSS that applies. The browser combines them into a render tree and paints from that.
If the browser painted before the CSS arrived, users would see unstyled content flash and then jump into place. To prevent this, browsers treat CSS as render blocking. The browser will not paint any content that depends on a pending stylesheet. Two things follow from this:
- The time to first paint depends on the slowest blocking stylesheet, not only on the HTML.
- Fewer bytes and fewer round trips before first paint make the page appear sooner.
The three methods differ in how much extra network work they cost and whether the result can be reused on later visits.
What blocks and what does not
Blocking behavior depends on how the CSS is attached.
| Method | Extra request? | Blocks first paint? | Reusable across pages? |
|---|---|---|---|
| `style` attribute | No | Only as part of the HTML | No, copied into each element |
| `style` element | No | Only as part of the HTML | No, copied into each page |
| `link` to a `.css` file | Yes | Yes, until the file loads or fails | Yes, through the browser cache |
| `link` with a non-matching `media` | Yes, at low priority | No | Yes |
Inline styles and style elements arrive with the HTML. The browser has them as soon as it parses them, so no extra network wait occurs. A linked stylesheet needs its own request, and the browser holds back rendering until that request finishes.
A stylesheet also blocks scripts. A script that appears after a pending <link rel="stylesheet"> will not run until the stylesheet has loaded. The script might read computed styles, so the browser must know the final values first. A slow stylesheet can therefore delay JavaScript as well as painting.
Request chains and `@import`
A browser starts to download stylesheets as soon as it sees them in the HTML. In fact, browsers run a lightweight preload scanner ahead of the main parser to find link elements early, so several stylesheets download in parallel.
@import breaks this. The browser can only see an @import rule after it has downloaded and parsed the CSS file that contains it.
/* main.css */
@import url("reset.css");
@import url("typography.css");
body {
margin: 0;
}If the HTML links main.css, the loading order is:
- Request
main.cssand wait for it. - Parse it and discover the imports.
- Request
reset.cssandtypography.css.
This is a two-step chain. If reset.css itself imports another file, the chain grows to three steps. Each step costs at least one network round trip, and rendering is blocked the whole time. Linking all files from the HTML avoids the chain:
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/typography.css">
<link rel="stylesheet" href="css/main.css">Here the browser can request all three at once. Build tools that bundle CSS usually resolve @import at build time, so the browser receives one file. That is a legitimate use. Raw @import in files you serve to the browser is the one to avoid.
Caching: where external files win
Every time a visitor loads a page, the HTML is fetched again, or at least revalidated. Inline CSS travels inside that HTML, so it is re-downloaded with every page view. A 20 KB stylesheet inlined into a 100-page site costs 20 KB on every page.
An external file can be cached. The server sends the file with caching headers, and the browser stores it. On later pages, the browser uses the stored copy without a network request, or with a very small one.
HTTP/1.1 200 OK
Content-Type: text/css
Cache-Control: public, max-age=31536000, immutable
ETag: "a1b2c3"Cache-Control: max-age=31536000 says the file may be reused without asking the server for one year, expressed in seconds. immutable tells the browser the file will not change at that URL, so it should not even revalidate on reload. ETag is a version tag. If a cached copy has expired, the browser sends the tag back, and the server can answer 304 Not Modified with no body.
The cache-busting problem
A long cache lifetime creates a problem. If you edit site.css and the browser has cached it for a year, returning visitors keep the old version. The common fix is to put a content hash in the file name, which is called fingerprinting:
<link rel="stylesheet" href="/css/site.3f9a1c7e.css">When the content changes, the hash changes, so the URL changes, and browsers fetch the new file as if it were a different resource. The HTML that references the file must then not be cached for long. A typical setup is Cache-Control: no-cache on HTML, which means "store it, but revalidate before use", and one-year immutable on fingerprinted CSS.
A query string such as site.css?v=2 is a simpler alternative. It works in browsers, but some intermediate caches handle query strings poorly, and you must remember to change it by hand.
First visit versus repeat visits
External CSS pays a cost on the first visit and gains on later ones:
- First visit: one extra request that blocks rendering. This is slower than inline CSS.
- Repeat visits: the file comes from cache, so the cost is close to zero. This is faster than inline CSS, which downloads again with each HTML response.
Inlining critical CSS
Some sites combine both approaches. They inline a small amount of critical CSS, the rules needed to draw the content visible without scrolling, and load the rest as an external file. The first paint no longer waits for a CSS request.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Critical CSS</title>
<style>
body { margin: 0; font-family: system-ui, sans-serif; }
header { background: #123; color: white; padding: 1rem; }
</style>
<link rel="stylesheet" href="/css/site.3f9a1c7e.css">
</head>
<body>
<header>Site name</header>
<main>Content</main>
</body>
</html>This example still blocks on the external file, because a plain link always blocks. To make the full stylesheet non-blocking, you can load it with a non-matching media value and switch it after loading:
<link rel="stylesheet" href="/css/site.3f9a1c7e.css"
media="print" onload="this.media='all'">
<noscript>
<link rel="stylesheet" href="/css/site.3f9a1c7e.css">
</noscript>The browser downloads a media="print" stylesheet without blocking screen rendering. When it finishes, the onload handler sets media to all and the rules apply. The noscript fallback covers visitors with JavaScript disabled.
This technique has costs:
- The page can paint with only the critical CSS, so any content the critical CSS misses may flash unstyled and then shift.
- The critical CSS is duplicated in every HTML response and is not cached separately.
- The
onloadattribute is an inline event handler. A strict Content Security Policy blocks it unless it permits it, which a later chapter covers. - Extracting critical CSS by hand is error-prone. Teams normally automate it in the build.
A rule of thumb for the size of the inline part: keep it small, often cited as roughly 14 KB compressed, so that it fits in the first round trip of a new TCP connection together with the rest of the HTML. Treat that number as a guide, not a limit set by the specification.
Telling the browser earlier
When the browser can only find a stylesheet late, you can hint at it. A preload link tells the browser to fetch a resource at high priority even though it has not been referenced yet:
<link rel="preload" href="/css/site.3f9a1c7e.css" as="style">
<link rel="stylesheet" href="/css/site.3f9a1c7e.css">The as="style" value is required. Without it, the browser cannot assign the correct priority and may fetch the file twice. Preload mainly helps when CSS is injected by script or reached through an @import chain. For a normal link in the head, the preload scanner already finds it, so preload adds nothing.
Splitting CSS by condition also helps. A print stylesheet or a stylesheet for wide screens only needs to block rendering when its condition is true:
<link rel="stylesheet" href="/css/base.css">
<link rel="stylesheet" href="/css/print.css" media="print">
<link rel="stylesheet" href="/css/wide.css" media="(min-width: 1200px)">On a narrow screen, wide.css is still downloaded, at low priority, but it does not hold back the first paint.
Common mistakes
- Using
@importin served CSS. This creates request chains. Uselinkelements or a bundler. - Putting
linkelements at the end ofbody. Rendering the content before the CSS arrives causes a flash of unstyled content. Keep stylesheets in thehead. - Caching CSS for a long time without fingerprinting. Users see stale styles after a deploy.
- Inlining everything on a multi-page site. Every page pays for all the CSS every time.
- Splitting CSS into dozens of tiny files. HTTP/2 and HTTP/3 reduce the cost of many requests, but each file still needs a response, and compression works better on larger files.
- Measuring only the first visit. Test with a cold cache and a warm cache, because the two give opposite results for inline versus external CSS.
Decision summary
| Situation | Good choice |
|---|---|
| Single page, small CSS, no repeat visits | `style` element |
| Multi-page site with returning visitors | External, fingerprinted, long cache |
| Large site where first paint matters | Small inline critical CSS plus external file |
| Rules for one print or wide-screen case | Separate `link` with a `media` attribute |
| Many CSS files merged in the source | Bundle at build time, not `@import` at run time |
Exercise
A site has 50 pages that all use the same 30 KB stylesheet. A visitor opens 10 of them in one session. Compare the CSS bytes transferred if the stylesheet is inlined into each page with the bytes transferred if it is a cached external file. Assume no compression.
Show answer
Inlined, the CSS is part of each HTML response, so the visitor downloads 10 x 30 KB = 300 KB of CSS. As a cached external file, the visitor downloads it once, 30 KB, and reuses it for the other nine pages. The external file also costs one extra blocking request on the first page. The savings grow with every additional page viewed.
Exercise
The file main.css contains @import url("theme.css"); and the HTML contains only <link rel="stylesheet" href="main.css">. Explain why the page may paint later than if the HTML linked both files directly, and show the fix.
Show answer
The browser can only discover theme.css after it has downloaded and parsed main.css, so the two downloads happen one after the other and each adds a round trip while rendering is blocked. If the HTML links both files, the browser requests them in parallel. The fix is to remove the @import and add <link rel="stylesheet" href="theme.css"> to the head, before or after the main.css link. The order matters for the cascade, so keep theme.css in the position the @import occupied.
Exercise
You set Cache-Control: max-age=31536000, immutable on site.css and then change the file. Returning visitors still see the old design. What two changes fix this for future updates?
Show answer
First, give the file a name that changes with its content, for example site.3f9a1c7e.css, so each version has its own URL. Second, update the link element in the HTML to point at the new name, and serve the HTML with Cache-Control: no-cache so browsers revalidate it and find the new link.