Skip to content
FrontDepth, Home

Browser & Performance

Critical Rendering Path

How the browser turns HTML, CSS and JavaScript into pixels — DOM, CSSOM, render tree, layout, paint and compositing — and what blocks or speeds up the first render.

JuniorMiddleSeniorUpdated 13 November 2026

Reading level

Shows sections up to the selected level.

Before you start

This topic starts at Junior level.

JuniorConcept

What the critical rendering path is

The (CRP) is the chain of steps the browser goes through between receiving the bytes of an HTML document and drawing pixels on the screen. "Critical" refers to the work and the resources that must be finished before the user sees the first meaningful content.

The steps

  1. HTML → DOM. The browser decodes the bytes into characters, splits them into tokens and creates nodes. The nodes form the tree.
  2. CSS → CSSOM. Stylesheets go through a similar process and produce the .
  3. Render tree. The browser combines the DOM and the CSSOM, computes the final style of every visible node and builds the .
  4. Layout. It calculates the exact size and position of every box (, also called reflow).
  5. Paint. It turns the boxes into drawing instructions: text, colors, borders, shadows, images ().
  6. Composite. It combines the painted layers into the final frame ().

Why the order matters

Each step depends on the previous ones. Layout cannot start before the render tree exists, and the render tree needs both the DOM and the CSSOM. So anything that delays one of the inputs — a slow stylesheet, a script that stops the HTML parser — delays the first paint as a whole. Optimizing the CRP means shortening this chain for the first screen: fewer resources that block rendering, fewer bytes, fewer network round trips.

The browser also works incrementally. It does not wait for the whole HTML file: it parses what has already arrived and can render the top of the page early.

Not only the first load

The pipeline does not run just once. After the page is shown, every DOM or style change made by JavaScript re-runs part of it: style, layout, paint, composite. The same knowledge helps you both load pages faster and keep interactions and animations smooth.

JuniorWeb platform

Building the DOM and the CSSOM

The HTML parser builds the incrementally: as chunks of HTML arrive over the network, new nodes are added to the tree. When the parser meets <link rel="stylesheet">, <img> or <script src>, the browser starts requesting those resources.

Stylesheets are parsed into the . Here the browser behaves differently: a half-loaded stylesheet is useless for rendering, because a rule at the end of the file can override a rule at the start — that is how the cascade works. So the browser waits until the whole stylesheet is downloaded and parsed.

CSS is render-blocking

By default, stylesheets in the <head> are : the browser does not render the page until they have loaded. Otherwise the user would first see unstyled content, and then the page would jump into its final look (FOUC — flash of unstyled content).

Note what CSS does not block: the HTML parser keeps going and the DOM keeps growing. Only rendering waits.

The media attribute changes this. A stylesheet whose media query does not match the current environment is still downloaded (usually with low priority), but it does not block rendering:

HTML
<link rel="stylesheet" href="main.css" />
<link rel="stylesheet" href="print.css" media="print" />
<link rel="stylesheet" href="wide.css" media="(min-width: 1024px)" />

Here main.css always blocks rendering, print.css never does on a screen, and wide.css blocks only when the viewport is at least 1024px wide.

Practical consequences

  • Put stylesheets in the <head> so they are discovered early.
  • Keep the CSS needed for the first screen small: every kilobyte of it delays the first paint.
  • Avoid @import inside CSS. The imported file is discovered only after the parent file has been downloaded and parsed, which adds one more round trip to the chain.
JuniorWeb platform

Render tree, layout and paint

The combines the DOM and the CSSOM, but it contains only what will actually be rendered. (In Chromium it is called the layout tree.)

Not in the render tree:

  • <head>, <script>, <meta>, <link> and other elements hidden by the browser's default styles;
  • elements with display: none — together with all their descendants.

In the render tree:

  • elements with visibility: hidden or opacity: 0 — they are invisible but still take up space;
  • ::before and ::after pseudo-elements with content — they are not in the DOM, yet they generate boxes.
StyleIn the DOMIn the render treeTakes up space
display: noneyesnono
visibility: hiddenyesyesyes
opacity: 0yesyesyes

You can observe this from JavaScript: an element with display: none has no box, so its geometry is zero.

JavaScript
const menu = document.querySelector(".menu");
menu.style.display = "none";
console.log(menu.offsetWidth); // 0

Layout, paint, composite

walks the render tree and calculates the geometry of every box: width, height, position. Percentages, line wrapping and font sizes are resolved here. When the viewport size changes, layout runs again.

records how to draw each box: backgrounds, borders, text, shadows, images. The page is often painted in several layers.

puts those layers together in the right order to produce the frame you see. Some elements — for example, one with an animated transform, or a <video> — often get their own layer, so they can move without repainting the rest of the page.

The first time this pipeline puts any text or image on the screen, the browser records .

MiddleWeb platform

Scripts, the parser and the preload scanner

A classic <script> without attributes is . When the parser reaches it, DOM construction stops. For an external script the browser waits for the download, executes the script and only then continues parsing. The reason: the script may change the document that is being parsed (for example, with document.write), so the parser cannot safely move on.

Scripts wait for CSS

A script may read styles (getComputedStyle, offsetWidth), so the browser does not run a script that the parser executes (inline or external, without async) while a stylesheet earlier in the document is still loading. A slow stylesheet followed by a script therefore blocks not only rendering but parsing too.

async, defer and modules

ScriptDownloadExecutionOrder
<script src>blocks the parserright after downloaddocument order
asyncin parallelas soon as downloaded (parsing pauses while it runs)not guaranteed
deferin parallelafter parsing, before DOMContentLoadeddocument order
type="module"in parallel, with its importsdeferred by default; async is alloweddocument order without async

async and defer only work on external classic scripts; on an inline classic script they are ignored. Module scripts, inline or external, are deferred by default.

DOMContentLoaded fires when the HTML is fully parsed and deferred scripts have run. It does not wait for images or async scripts. The load event waits for all subresources, including images and stylesheets.

The preload scanner

While the main parser is blocked by a script, the browser does not sit idle. The reads ahead in the raw HTML and starts downloading the resources it finds: <img>, <link rel="stylesheet">, <script src>. It is one of the most important browser optimizations, but it only sees what is written in the HTML markup. It cannot discover:

  • resources added by JavaScript (including everything a client-rendered app creates);
  • background-image URLs and fonts referenced in CSS;
  • images whose real URL hides in data-src until a script swaps it in.

These late-discovered resources are a common reason for a slow first render.

MiddleWeb platform

Updates after load: layout, paint, compositing

After the first render the pipeline keeps running. When something changes, the browser goes through some of these stages before the next frame: JavaScript → style → layout → paint → composite. Which stages run depends on what changed:

ChangeExample propertiesStages
Geometrywidth, height, margin, padding, top, font-size, adding nodesstyle → layout → paint → composite
Appearance onlycolor, background-color, box-shadowstyle → paint → composite
Transform / opacitytransform, opacityoften composite only

Layout is usually the most expensive part: resizing one element can move its siblings, its parent and its children. transform and opacity changes can often be handled by the compositor alone when the element is on its own layer. The details differ between engines, so check them in DevTools instead of memorizing lists.

Rendering and the event loop

Rendering happens between tasks. After a task and all its finish, the browser may update the rendering: it runs callbacks, recalculates style and layout, then paints. A long task on the means no new frame until it ends.

Forced synchronous layout

Normally layout is lazy: you change styles, and the browser computes layout once, before the next frame. But if JavaScript reads geometry after a style change — offsetWidth, offsetHeight, getBoundingClientRect(), scrollTop, layout-dependent values from getComputedStyle() — the browser must run layout immediately to return a correct value. This is a .

Doing it in a loop is :

JavaScript
for (const item of items) {
  item.style.width = `${container.offsetWidth / 2}px`;
}

Every read follows a write, so layout runs on every iteration. Read once, then only write:

JavaScript
const half = container.offsetWidth / 2;
for (const item of items) {
  item.style.width = `${half}px`;
}

The rule: batch reads first, then writes, and schedule visual writes with requestAnimationFrame. The DevTools Performance panel marks forced reflows with a warning.

MiddlePitfalls

Common pitfalls

  • Blocking scripts in the <head>. A <script src> without defer stops parsing until the file is downloaded and executed; meanwhile the user stares at a blank page. Use defer or type="module".
  • Expecting async to keep the order. async scripts run as soon as they are downloaded. If plugin.js depends on library.js, making both async leads to random "library is not defined" errors. Use defer for scripts that depend on each other.
  • @import chains in CSS. Every @import adds a sequential request: the browser discovers the child file only after parsing the parent.
  • Hiding the page until JavaScript is ready. Patterns like body { opacity: 0 } removed later by a script make the browser paint an invisible page; the content effectively appears only when the script runs.
  • Lazy-loading above-the-fold images. loading="lazy" on the hero image delays its request until the browser knows, after layout, that the image is near the viewport. This typically hurts .
  • Measuring layout in loops and scroll handlers. Changing styles and then reading offsetHeight in a loop causes .
  • Animating geometry. Animating top, left, width or height runs layout on every frame. Animate transform and opacity when possible.
  • Treating display: none as free. The element is not rendered, but it is still in the DOM, and an <img> inside it is typically still downloaded.
  • Using DOMContentLoaded as a performance metric. It tells you that parsing finished, not what the user sees. For that, look at and LCP.
SeniorWeb platform

Optimizing the critical rendering path

Three numbers describe a CRP: the number of critical resources (render- or parser-blocking), the critical bytes they add up to, and the critical path length — how many sequential network round trips are needed (HTML → CSS → @import → font is four). Every optimization reduces one of them. For the HTML itself, a fast server response, compression (Brotli or gzip), HTTP caching and a CDN cut bytes and round trips.

CSS and JavaScript

  • Inline the — the rules needed for the first screen — in a <style> in the <head>, and load the rest without blocking. The trade-off: inlined CSS is not cached separately and is sent with every HTML response, so keep it small and generate it with tooling.
  • Split CSS by media so files that don't match don't block rendering.
  • Use defer or type="module" for application code and async for independent third-party scripts. Ship less JavaScript before the first paint: whatever has to run first occupies the .

Discovery and priority

  • <link rel="preload"> exposes resources hidden in CSS or JavaScript to the browser early: the main font, or a background image that is the element.
  • Put fetchpriority="high" on the LCP image. The browser cannot know which image is the LCP one before layout, so such images often start at a lower priority.
  • Never lazy-load above-the-fold images. preconnect to critical third-party origins.

Don't preload everything: preloads compete for bandwidth with truly critical resources, and Chrome warns in the console when a preloaded resource is not used within a few seconds of the load event.

Fonts

Browsers start downloading a font only once they know that rendered text uses it, i.e. after style calculation. Preload the one or two fonts the first screen needs (font preloads require crossorigin). font-display: swap shows fallback text immediately and swaps in the font when it arrives; optional gives the font a very short window and otherwise keeps the fallback, which avoids a late layout shift.

HTML
<head>
  <style>/* critical rules */</style>
  <link rel="preload" href="/fonts/inter.woff2" as="font" type="font/woff2" crossorigin />
  <link rel="stylesheet" href="/css/main.css" media="print" onload="this.media='all'" />
  <script src="/js/app.js" defer></script>
</head>
<body>
  <img src="/img/hero.avif" alt="Product photo" width="1200" height="600" fetchpriority="high" />
</body>

The media="print" + onload pattern downloads main.css without blocking rendering and applies it once it has loaded.

SeniorFramework

React and the critical rendering path

Client-only rendering

In a client-rendered app (createRoot in a Vite SPA, for example) the HTML is basically <div id="root"></div> plus a script. The CRP becomes: HTML → download the bundle → parse and execute it → React renders → DOM → layout → paint. and wait for the whole bundle, and the LCP image is invisible to the because the <img> only exists after React has run.

SSR and streaming

With server rendering (renderToPipeableStream / renderToReadableStream, or a framework such as Next.js) the content is in the HTML, so the browser can paint it before any JavaScript loads. With <Suspense>, React streams the shell first and sends the remaining HTML later, together with an inline script that replaces the fallback.

The price is : hydrateRoot must download the component code and render it again on the client to attach event handlers. Until then the page looks ready but doesn't respond, and hydration itself is main-thread work that grows with the size of the tree. Suspense boundaries let React hydrate parts of the page independently instead of all at once.

React 19 resource APIs

react-dom exports preload (fetch a resource), preinit (fetch and execute a script, or fetch and insert a stylesheet), preconnect and prefetchDNS. In server rendering they only have an effect when called while rendering a component, and they end up as tags in the HTML; in the browser they can be called anywhere — for example, in a click handler before navigating.

A <link rel="stylesheet"> with a precedence prop gets special treatment: React places it in the <head> wherever it is rendered, de-duplicates it by href and orders stylesheets by precedence. During SSR it is included in the <head>, so the browser won't paint until it has loaded; on the client, the component suspends while the stylesheet is loading.

TSX
import { preinit, preload } from "react-dom";

type Props = { title: string; imageUrl: string };

export function ProductHero({ title, imageUrl }: Props) {
  preload("/fonts/inter.woff2", { as: "font", type: "font/woff2", crossOrigin: "anonymous" });
  preinit("https://widgets.example.com/reviews.js", { as: "script" });

  return (
    <section>
      <link rel="stylesheet" href="/css/hero.css" precedence="default" />
      <h1>{title}</h1>
      <img src={imageUrl} alt={title} fetchPriority="high" />
    </section>
  );
}
SeniorInterview tips

Interview tips

  • Name the stages in order and say what blocks what. HTML → DOM, CSS → CSSOM, render tree, layout, paint, composite. A compact summary: CSS blocks rendering; classic scripts block parsing; CSS also delays script execution, so a slow stylesheet can block parsing indirectly.
  • Separate load from runtime. The CRP is about the first render, but the same pipeline (style → layout → paint → composite) runs on every update. Be ready to discuss , and why transform animations are cheaper than animating top or width.
  • Start from measurements, not guesses. For a slow page: run Lighthouse for lab numbers and its list of render-blocking requests; record the page in the DevTools Performance panel to see the FCP and LCP markers, long tasks and layout events; check the Network panel waterfall for request chains and priorities. Then compare with field data (CrUX, the web-vitals library), because a lab run is not your real users.
  • Break LCP down. LCP = time to first byte + resource load delay + resource load duration + element render delay. The largest part points to the fix: a slow server, a late-discovered image, a heavy image, or rendering blocked by CSS and JavaScript. A good is 2.5 seconds or less, measured at the 75th percentile of page loads.
  • Talk about trade-offs. Inlined critical CSS vs caching; SSR (faster first paint) vs hydration cost; preloading vs bandwidth contention; font-display: swap vs layout shift.
  • Avoid common misstatements: "CSS blocks HTML parsing" (it blocks rendering and script execution), "async and defer are the same", "display: none and visibility: hidden are equivalent".
JuniorReview checklist

What to check when reviewing changes to the critical rendering path

Use this list when you review a change you did not write (a teammate's pull request, a library's snippet or an AI assistant's suggestion) to the <head>, scripts, stylesheets, fonts or first-screen images. One blocking script or a late-found hero image can leave users staring at a blank page.

  • Does every new <script src> have defer, async or type="module", and are scripts that depend on each other defer, not async? Without them, a classic script is : parsing stops until it downloads and runs. async scripts run as soon as they arrive, so a plugin can run before its library.
  • Is the main first-screen image a real <img> in the HTML, without loading="lazy"? The sees only markup, not images added by JavaScript or a CSS background-image, and lazy loading waits for layout. Find the LCP element in the Performance panel; give it fetchpriority="high".
  • Does the change add @import, a large stylesheet, or print CSS without media? Stylesheets in the <head> are , and each @import adds a round trip. Lighthouse lists the render-blocking requests.
  • Are fonts and images hidden in CSS or JavaScript that the first screen needs preloaded, and only those? Font preloads need crossorigin. Extra preloads compete for bandwidth; Chrome warns about unused ones.
  • Is the page hidden until a script runs? With body { opacity: 0 } removed by JavaScript, the content appears only once the script runs.
  • In a React app, does first-screen content move from server-rendered HTML to client-only rendering? Then and wait for the whole bundle.
  • Is the gain measured with FCP and LCP, not DOMContentLoaded? That event only says parsing finished. Compare Performance recordings before and after.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    3 predict-output · 4 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    6 questions