Internet Frontend 03 ๐ The Critical Rendering Path
The Critical Rendering Path is the sequence of steps the browser takes to convert HTML, CSS, and JavaScript into pixels on the screen. It is not a single operation but a pipeline of distinct stages, and each stage depends on the one before it. The DOM must exist before styles can be resolved. The CSSOM must be complete before the render tree can be built. The render tree must be laid out before anything can be painted. The pipeline is the browser’s dependency graph, and the critical path is the longest chain of dependencies that must be resolved before the first pixel appears .
The “critical” part is the part that blocks rendering. A stylesheet in the <head> blocks rendering because the browser cannot paint a page with incomplete styles; a partial CSSOM would render the wrong colors, the wrong spacing, the wrong layout, and then repaint when the rest of the CSS arrives. A synchronous <script> in the <head> blocks parsing because the script can call document.write() and change the document structure mid-parse . The browser trades initial latency for correctness, and the optimization is the discipline of shortening the critical path without breaking the correctness.
Key point: The Critical Rendering Path is DOM construction, CSSOM construction, render tree construction, layout, paint, and compositing. CSS is render-blocking because a partial CSSOM would render the wrong styles. Synchronous scripts are parser-blocking because they can mutate the document. The optimization is to shorten the path: inline critical CSS, defer non-critical scripts, and avoid layout thrashing.
Why the path is the performance model
The dependency chain problem. The browser cannot paint before it lays out, cannot lay out before it builds the render tree, cannot build the render tree before it has both the DOM and the CSSOM, and cannot build the DOM before it parses the HTML. Each stage is a prerequisite for the next, and the chain is the critical path . A delay at any stage propagates to every stage after it. A stylesheet that takes 200 milliseconds to download adds 200 milliseconds to the first paint, regardless of how fast the rest of the pipeline is.
The blocking problem. The HTML parser is incremental. It can build the DOM as bytes arrive, and it can discover resources early with the preload scanner . But a <script> without async or defer halts the parser, because the script might change the document. A <link rel="stylesheet"> does not halt the parser, but it blocks rendering, because the browser will not paint until the CSSOM is complete . The blocking is the mechanism that protects correctness, and the optimization is the mechanism that reduces the time the blocking lasts.
The thread problem. The style, layout, and paint setup stages run on the main thread, which is the same thread that runs JavaScript. A long JavaScript task blocks the style resolution and the layout, which means the first paint is delayed by the JavaScript even if the DOM and CSSOM are ready . The main thread is the single resource that the pipeline and the application share, and the contention is the reason the critical path is not only about download time.
The trade-off. The critical path optimization is a trade-off between the initial paint and the correctness. Inlining critical CSS makes the first paint faster, but it increases the HTML size and the cache granularity. Deferring non-critical scripts makes the parser faster, but it delays the script execution. The optimization is the discipline of deciding which resources are on the critical path and which can wait.
a. The DOM and CSSOM construction
The DOM is built incrementally. The browser reads the HTML bytes, converts them to characters, tokenizes the characters into tags, and builds the nodes into a tree. The tree captures the parent-child relationships of the markup . The construction is incremental because the parser can add nodes as the bytes arrive, and the preload scanner can discover the external resources before the main parser reaches them .
The CSSOM is built from the CSS, and it is not incremental. The CSS cascade means that a later rule can override an earlier rule, so the browser must parse the entire stylesheet before it can resolve the final style for any element. The CSSOM is the tree of the resolved rules, and it is complete before the render tree can be built . The difference between the incremental DOM and the non-incremental CSSOM is the reason CSS is render-blocking: the browser cannot paint a partial result, because the partial result would be the wrong result.
<!-- The synchronous script blocks the parser -->
<head>
<script src="blocking.js"></script> <!-- parser-blocking -->
<link rel="stylesheet" href="styles.css"> <!-- render-blocking -->
</head>
The blocking.js script halts the parser until it is downloaded, parsed, and executed. The styles.css stylesheet does not halt the parser, but it blocks the render until it is downloaded and parsed. The two blocking mechanisms are different, and the optimization for each is different.
b. The render tree, layout, and paint
The render tree is the combination of the DOM and the CSSOM. The browser walks the DOM, and for each visible node, it attaches the resolved styles from the CSSOM. The render tree does not include the <head> or the nodes with display: none, because those nodes do not produce a visual box . The render tree is the structure that the layout stage operates on.
The layout stage computes the geometry. It walks the render tree and calculates the position and size of each box, relative to the viewport. The layout is the stage that turns the tree into coordinates . The layout is expensive because the position of one element can affect the position of every element after it, and the browser must resolve the cascade of the box model, the floats, the flexbox, and the grid.
The paint stage converts the laid-out boxes into the drawing commands, and the compositing stage assembles the layers into the final image . The paint is the stage that fills the pixels, and the compositing is the stage that combines the layers. The two stages are the last in the pipeline, and they are the stages that the CSS transform and opacity animations can skip, because those properties do not change the layout .
Complete Example Session
// ============================================
// PART 1: THE BLOCKING RESOURCES
// ============================================
// A synchronous script blocks the parser.
// <script src="app.js"></script>
// A stylesheet blocks the render.
// <link rel="stylesheet" href="styles.css">
// ============================================
// PART 2: THE CRITICAL CSS INLINING
// ============================================
// The critical CSS is the CSS for the above-the-fold content.
// It is inlined in the <head> to avoid the render-blocking request.
<style>
body { margin: 0; font-family: system-ui; }
.hero { min-height: 100vh; }
</style>
// The rest of the CSS is deferred.
<link rel="preload" href="non-critical.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
// ============================================
// PART 3: THE SCRIPT DEFERRING
// ============================================
// The non-critical scripts are deferred.
// They do not block the parser.
<script defer src="app-bundle.js"></script>
// The async attribute is for the independent scripts.
<script async src="analytics.js"></script>
// ============================================
// PART 4: THE LAYOUT THRASHING
// ============================================
// โ The layout thrashing: read and write in the same loop.
for (const el of elements) {
const height = el.offsetHeight; // read (forces layout)
el.style.height = height + 10 + 'px'; // write (invalidates layout)
}
// โ
The batch: read all, then write all.
const heights = elements.map(el => el.offsetHeight);
elements.forEach((el, i) => { el.style.height = heights[i] + 10 + 'px'; });
// ============================================
// PART 5: THE MAIN THREAD YIELDING
// ============================================
// A long task blocks the style and layout.
// The task is split with scheduler.yield().
async function processLargeList(items) {
for (let i = 0; i < items.length; i++) {
if (i % 50 === 0) {
await scheduler.yield(); // yield to the main thread
}
// process the item
}
}
// ============================================
// PART 6: THE COMPOSITOR-FRIENDLY ANIMATION
// ============================================
// โ
The transform and opacity animations skip layout and paint.
// They run on the compositor thread.
.element { transition: transform 0.3s, opacity 0.3s; }
// โ The top and left animations trigger layout and paint.
.element { transition: top 0.3s, left 0.3s; }
// ============================================
// PART 7: THE RESOURCE HINTS
// ============================================
// The preconnect for the critical third-party domains.
<link rel="preconnect" href="https://fonts.example.com">
// The preload for the critical asset.
<link rel="preload" href="/hero.webp" as="image" fetchpriority="high">
// ============================================
// PART 8: THE CONTENT VISIBILITY
// ============================================
// The off-screen content is skipped with content-visibility.
.offscreen-section {
content-visibility: auto;
contain-intrinsic-size: 0 500px; // placeholder height
}
// ============================================
// PART 9: THE VERIFICATION
// ============================================
// The Chrome DevTools Performance panel shows the pipeline.
// The "Critical Rendering Path" is the chain of the blocking resources.
// The "Render-blocking requests" insight lists the blocking resources.
// ============================================
// PART 10: THE CHECKLIST
// ============================================
// [ ] The critical CSS is inlined.
// [ ] The non-critical CSS is deferred.
// [ ] The synchronous scripts are deferred or async.
// [ ] The third-party scripts use defer.
// [ ] The layout thrashing is avoided.
// [ ] The long tasks are split.
// [ ] The compositor-friendly animations are used.
// [ ] The resource hints are set for the critical domains.
The ten parts covered the blocking resources, the critical CSS inlining, the script deferring, the layout thrashing, the main thread yielding, the compositor-friendly animation, the resource hints, the content visibility, the verification, and the checklist. The through-line is that the pipeline is the dependency chain, and the optimization is the discipline of shortening the chain.
Quick Reference
The pipeline stages
| Stage | Input | Output |
|---|---|---|
| DOM construction | HTML bytes | DOM tree |
| CSSOM construction | CSS bytes | CSSOM tree |
| Render tree | DOM + CSSOM | Render tree |
| Layout | Render tree | Box geometry |
| Paint | Laid-out boxes | Drawing commands |
| Compositing | Drawing commands | Pixels |
The blocking resources
| Resource | Blocks | Fix |
|---|---|---|
Synchronous <script> | Parser | defer or async |
<link rel="stylesheet"> | Render | Inline critical CSS, defer the rest |
@import in CSS | CSSOM | Avoid; use <link> |
| Long JavaScript task | Style, layout | Split with scheduler.yield() |
The optimization techniques
| Technique | Purpose |
|---|---|
| Inline critical CSS | Avoid the render-blocking request |
defer / async | Avoid the parser-blocking script |
preconnect / preload | Start the critical fetches early |
| Batch DOM reads/writes | Avoid layout thrashing |
transform / opacity | Skip layout and paint |
content-visibility | Skip the off-screen layout |
Best Practices
โ Do This:
<!-- Inline the critical CSS -->
<style>.hero { min-height: 100vh; }</style>
<!-- Defer the non-critical scripts -->
<script defer src="app-bundle.js"></script>
// Batch the DOM reads and writes
const heights = elements.map(el => el.offsetHeight);
elements.forEach((el, i) => { el.style.height = heights[i] + 'px'; });
โ Don’t Do This:
<!-- Block the parser with a synchronous script -->
<script src="app-bundle.js"></script>
/* Use @import, which creates a sequential request chain */
@import url("styles.css");
// Read and write in the same loop (layout thrashing)
for (const el of elements) {
el.style.height = el.offsetHeight + 'px';
}
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| The first paint is delayed by a stylesheet | The CSS is render-blocking | Inline the critical CSS |
| The parser is blocked by a script | The script is synchronous | Use defer or async |
| The animation is janky | The animation triggers layout | Use transform and opacity |
| The main thread is blocked | A long JavaScript task | Split the task with scheduler.yield() |
| The layout is slow | The DOM is large | Use content-visibility for the off-screen content |
Summary
| Item | Value |
|---|---|
| Pipeline stages | DOM, CSSOM, render tree, layout, paint, composite |
| Parser-blocking | Synchronous <script> |
| Render-blocking | CSS in the <head> |
| Critical CSS | Inline the above-the-fold styles |
| Script deferring | defer or async |
| Layout thrashing | Read and write in the same loop |
| Compositor-friendly | transform and opacity |
Key takeaways:
- The critical rendering path is a dependency chain. The DOM must be built before the render tree, the CSSOM must be complete before the render tree, the render tree must be laid out before the paint, and the paint must be finished before the composite . A delay at any stage propagates to every stage after it.
- CSS is render-blocking because a partial CSSOM is the wrong result. The cascade means that a later rule can override an earlier one, so the browser must parse the entire stylesheet before it can resolve the final style. The blocking is the price of correctness .
- Synchronous scripts are parser-blocking because they can mutate the document. A
<script>withoutasyncordeferhalts the HTML parser, because the script might calldocument.write()and change the document structure. Thedeferandasyncattributes are the escape hatches . - The main thread is shared between JavaScript and the pipeline. A long JavaScript task blocks the style resolution and the layout, which delays the first paint. The task is split with
scheduler.yield()to let the browser process the pending work . - The layout thrashing is the performance bug that the pipeline exposes. Reading
offsetHeightforces a synchronous layout, and writingstyle.heightinvalidates it. The loop that does both forces a layout per iteration. The fix is to batch the reads and the writes .
Remember: The Critical Rendering Path is the browser’s dependency graph. The DOM and the CSSOM feed the render tree, the render tree feeds the layout, the layout feeds the paint, and the paint feeds the composite. The blocking resources are the ones that must be resolved before the next stage can run, and the optimization is the discipline of shortening the path without breaking the correctness. The critical CSS is inlined, the non-critical scripts are deferred, the long tasks are split, and the animations use the compositor-friendly properties. The pipeline is the model, and the model is the performance.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!