The Web FrontendVol. 2 · Part II
0 / 0

Shelves / The Web Frontend

FE·18

Browser Internals

What happens between typing a URL and seeing pixels: the multi-process architecture, sandboxing and site isolation, and the rendering pipeline (parse, style, layout, paint, composite), with the invalidation rules that decide frontend performance.

33 topics · ~26 min read · 26-question quiz
Updated Suggest a correction

Start here: what the browser does to show a page

From pressing Enter to seeing pixels

When you type a URL and press Enter, the browser works through a fixed sequence. In plain words:

  1. Find the server. Look up the host name in DNS to get an IP address, like finding a phone number in a directory.
  2. Connect. Open a connection to that address (a TCP handshake, or QUIC for HTTP/3), then agree on encryption (TLS) so nobody in between can read or change the traffic.
  3. Ask. Send the HTTP request; the server streams back the response: a status, headers and the HTML.
  4. Build the trees. Parse the HTML into the DOM and the CSS into the CSSOM (chapter 12), fetching every other file the page needs on the way.
  5. Style. Work out the final value of every CSS property for every element (the cascade, chapter 14).
  6. Layout. Work out the size and position of every box.
  7. Paint. Turn boxes into drawing instructions: fill this rectangle, draw this text, this border, this image.
  8. Composite. Rasterise those drawings into pixels on the GPU, in separate layers, and stack the layers into the final image on screen.

Steps 1–3 are networking (chapter 19 and Volume 1 chapter 9); steps 4–8 are rendering, the subject of this chapter. On a first visit to a distant server the networking dominates; on a busy page the rendering does; on most single-page apps, running JavaScript does. Knowing which step costs what is the foundation of frontend performance (chapter 27).

The rendering pipeline

JavaScript Style Layout Paint Composite change width, add elements change colour, background change transform, opacity
The rendering pipeline. After style is recalculated, geometry changes re-run layout, paint and composite; colour changes skip layout; transform and opacity changes only need compositing

Think of a newspaper being put together. Style decides each article's font and colours; layout decides where each article goes on the page and how much space it takes; paint draws the text and pictures; compositing stacks finished sheets (an advert printed separately, say) into the final page. If an editor changes a headline's colour, nothing needs to move: only that bit is repainted. If an article gets longer, everything below it must be laid out again. And if a separately printed advert just slides across the page, nothing is redrawn at all: the printer moves the sheet.

That's the most practical fact in this chapter: a change only re-runs the pipeline from the first stage it affects:

You change… Work the browser redoes Cost
size, position, fonts, content (width, top, font-size, adding elements) style → layout → paint → composite highest: can affect many other boxes
colours, backgrounds, shadows style → paint → composite medium
transform, opacity (on an element with its own layer) style → composite lowest: done on the GPU, can even run without the main thread

So animations should move things with transform: translate(…) instead of left/top, and fade with opacity. The lab counts the work each kind of change causes, using Chromium's own counters.

Frames: a flip book at 60 pages a second

A screen typically refreshes 60 times a second (120 on many phones). Each refresh shows a frame. For an animation or scroll to look smooth, the browser must produce a new frame every 16.7 ms (8.3 ms at 120 Hz), and it can only do that when the main thread, where your JavaScript, style and layout all run, is free. A JavaScript task that runs for 200 ms means no new frames for 200 ms: the page janks (stutters) and clicks go unanswered (chapter 15's lab measured exactly this).

The compositor runs on a separate thread, which is why a transform animation can keep moving smoothly even while JavaScript is busy, and why scrolling usually stays smooth on a busy page.

Why the browser is many programs

A browser isn't one program but several cooperating processes (Volume 1 chapter 8): one browser process for the window, tabs and permissions; a network process; a GPU process; and many renderer processes that run web pages. Each renderer is sandboxed: it can't read your files or open network connections itself, only ask the browser process. Pages from different sites run in different renderers (site isolation), so a malicious site can't read another site's memory even if it finds a bug in the browser. The lab shows Chromium starting a separate process for a cross-site iframe. One crashed tab ("Aw, Snap!") doesn't take the rest of the browser down for the same reason.

Seeing it for yourself

Open DevTools → Performance, press record, interact with a page for a few seconds, and stop. The flame chart shows every task on the main thread, colour-coded: yellow for scripting, purple for style and layout, green for paint and composite. Long tasks get a red corner. That's the same pipeline this section described, measured on a real page. Rendering (in the ⋮ → More tools menu) can flash every repainted area green ("Paint flashing") and outline layers, which makes "what does this change cost?" visible while you use the page.

How deep to go in browser internals

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 List the steps from URL to pixels and the browser's main processes
L2 Write code that avoids needless layout and paint; animate with transform and opacity
L3 Explain the process model, sandboxing, site isolation, the preload scanner, invalidation, layers and the compositor thread
L4 Diagnose jank, forced reflows, huge style recalculations and layer explosions in the Performance and Rendering panels
L5 Design pages and components around rendering costs: containment, content-visibility, layer strategy, DOM size
L6 Track rendering performance across a fleet of devices and browser releases; understand engine differences

From URL to pixels

The whole journey

The classic interview question "what happens when you type a URL and press Enter?" ties together everything in Volumes 1 and 2:

Text
URL
→ DNS            resolve the host (browser cache → OS → recursive resolver)      Vol. 1 ch. 9
→ connection     TCP three-way handshake (or QUIC for HTTP/3)                   Vol. 1 ch. 9
→ TLS            certificate validation, key exchange (1-RTT in TLS 1.3)        Vol. 1 ch. 9
→ HTTP           request with headers/cookies; response streams back           chapter 19
→ response       status, headers (Content-Type, caching, security headers)
→ parsing        HTML tokenizer + tree builder → DOM; preload scanner fetches ahead
→ DOM/CSSOM      CSS parsed → CSSOM; scripts may run and mutate the DOM
→ style          match selectors, cascade → computed style per element
→ layout         geometry: positions and sizes of every box
→ paint          drawing commands per layer
→ compositing    layers rasterised (GPU) and composited into the final frame

Each arrow can be the bottleneck. DNS and connection setup dominate on a cold visit to a far-away server. Render-blocking CSS and JavaScript dominate a heavy page. Style and layout dominate a huge DOM, and JavaScript execution dominates most single-page apps. Chapter 27 is about measuring which arrow costs you the most. This chapter explains how each one works.

Before the network: the browser first checks whether the input is a URL or a search query, applies HSTS (chapter 28: upgrade to https if the domain is on the preload list or sent the header before), checks the back-forward cache and service worker, and may already have preconnected or prerendered the page through speculation rules or the omnibox prediction.

Browser architecture

Browser processes

Modern browsers are multi-process applications, applying Vol. 1 ch. 8's process isolation to web content. Chromium's architecture (Firefox's Fission and Safari's WebKit2 are similar in spirit):

browser processUI, tabs, navigation,permissions, IPC broker network service GPU process storage service utility (audio, decode…) renderer: shop.exampleBlink + V8 main threadcompositor + raster threadsworkers renderer: ads.example(a cross-site iframe:own process) renderer: other tabsandboxed: no files,no sockets, no devices Mojo IPC
Chromium's process model. Renderers are sandboxed and can do almost nothing directly; they ask the browser process over IPC.
  • Browser process: the trusted coordinator. It handles the UI (address bar, tabs), navigation, the permission prompts, file access, and brokering everything the renderers request.
  • Renderer processes: they run Blink (HTML/CSS/DOM, the main thread), V8 (JavaScript), the compositor and raster threads, and workers. This is where web content runs, so it's untrusted.
  • Network service: all HTTP, caching, cookies and CORS enforcement.
  • GPU process: talks to the graphics driver, and rasterises and composites for every renderer.
  • Storage, audio and utility processes: isolated so that a crash or an exploit in one can't take down the rest.

Benefits: a crashing tab (the "Aw, Snap!" page) doesn't kill the browser; a compromised renderer has almost no OS privileges; and the OS scheduler spreads tabs across cores. The cost is memory, since every process has overhead. Chromium therefore consolidates renderers on low-memory devices, and tab discarding freezes background tabs.

Sandboxing

A sandbox confines a process to the minimum privileges it needs, using the OS mechanisms from Vol. 1 ch. 8: seccomp-bpf system-call filters and namespaces on Linux, restricted tokens and integrity levels on Windows, and the Seatbelt sandbox on macOS. A renderer can't open files, create sockets, launch processes or reach most system calls. It must ask the browser process over IPC, and the browser process checks each request against the origin's permissions.

Browser exploits therefore usually come as chains: one bug to get code execution in the renderer (often a V8 JIT bug), plus a second sandbox escape bug in the browser process, GPU process or kernel. Both are needed to compromise the machine. Defences in depth include V8's own heap sandbox (pointer compression and an isolated memory region, so corrupted JS objects can't reach arbitrary memory), MiraclePtr/BackupRefPtr against use-after-free in C++, and memory-safe languages for new components (Chromium and Firefox are adding Rust code; Vol. 1 ch. 2).

Site isolation

Process-per-tab isn't enough. A malicious page could embed <iframe src="https://bank.example">. With both in one process, a renderer bug, or a Spectre side channel (Vol. 1 ch. 7), could read the bank's memory. Site isolation puts each site (scheme + eTLD+1, chapter 12) in its own renderer process, including cross-site iframes ("out-of-process iframes"), so another site's data simply isn't in the attacker's address space.

Supporting mechanisms:

  • CORB/ORB (cross-origin read blocking): the network service refuses to deliver cross-origin JSON, HTML and XML responses to a renderer that requested them as an image or script. They'd never be usable there, and they could leak through side channels.
  • Cross-origin isolation (COOP + COEP headers, chapter 28) guarantees a page shares its process with no cross-origin documents, which re-enables precise timers and SharedArrayBuffer.
  • Partitioned storage and caches: the HTTP cache, cookies (CHIPS) and storage are keyed by the top-level site too, so embedded iframes can't track users across sites or probe whether a resource is cached from another site.

The rendering pipeline

Parsing: HTML to DOM, CSS to CSSOM

HTML parsing happens in two stages, both specified exactly in the HTML standard:

  1. Tokenisation: a state machine turns bytes (decoded using the charset) into tokens: start tags, end tags, text, comments.
  2. Tree construction: a second state machine builds the DOM from the tokens, applying error-recovery rules (chapter 12), and handles <script> tags.

Scripts interrupt parsing. When the tree builder meets a classic <script>, it must stop, because the script might call document.write and change everything that follows. While the parser waits, the preload scanner reads ahead in the raw HTML and starts downloading images, stylesheets and scripts it finds. That's why resources declared in the HTML are fast, and resources discovered later (CSS background-image, @import, JS-injected scripts, fonts referenced from CSS) are slow unless you preload them.

HTML is parsed incrementally as bytes arrive. The browser can start rendering the top of the page while the rest is still downloading. That's what streaming SSR exploits (chapter 24): flush the <head> and the shell immediately, then stream the rest.

CSS parsing produces the CSSOM. CSS is render-blocking: the browser won't paint until all the stylesheets in the <head> have loaded and parsed, to avoid a flash of unstyled content. It's also script-blocking: a script that comes after a stylesheet waits for that stylesheet, because the script might read computed styles.

Style

Style calculation (recalc style) determines the computed style of every element: match every rule's selectors against the element (right to left, using bloom filters of ancestor classes and IDs to reject quickly), apply the cascade and inheritance (chapter 14), and resolve relative values. The output is a ComputedStyle per element. Elements with display: none get no layout box.

The cost scales with number of elements × number and complexity of rules that could match. Style recalcs are scoped: changing a class on one element invalidates only the elements whose style might be affected, and the engine tracks dependencies to work this out. Broad selectors like :has() on large subtrees, or adding a class to <body> that matches descendant selectors (a theme switch), can invalidate thousands of elements.

Layout

Layout (reflow) computes the geometry of every box: its position and size, line breaks, the flex and grid algorithms (chapter 14), table sizing, and text shaping. The output is a layout tree, also called the fragment tree. It doesn't match the DOM one-to-one: display: none elements are missing, and pseudo-elements and anonymous boxes are added.

Layout is expensive and contagious. A change can affect siblings, parents and children: an element growing taller pushes everything below it down, and a change to a flex item resizes its siblings. Engines limit the work with dirty bits (only re-lay-out what's marked dirty), layout boundaries (fixed-size or contain: layout elements stop propagation upward), and caching. LayoutNG, Chromium's layout engine, produces immutable fragment trees that are cheaper to cache and reuse.

Layout invalidation

Each kind of change costs a different amount, depending on which pipeline stages it invalidates:

Change Style Layout Paint Composite Example
Geometry (width, height, margin, top, font-size, adding DOM nodes, text content) ✓ ✓ ✓ ✓ Expanding an accordion with height
Paint-only (color, background, box-shadow, border-radius, visibility) ✓ — ✓ ✓ Hover colour change
Compositor-only (transform, opacity, and filter on a composited layer) ✓ — — ✓ Sliding a drawer with transform: translateX()

That's why animation advice says: animate only transform and opacity. They can run entirely on the compositor thread, smoothly, even when the main thread is busy. Animating top, left, width or height re-runs layout on every frame. The CSS Triggers reference lists which stages each property invalidates per engine.

Forced synchronous layout and layout thrashing

Normally the browser batches: your script makes many DOM and style changes, and style and layout run once, before the next frame. But reading a geometry value after a write forces the browser to run style and layout immediately (synchronously) so it can give you a correct answer. This is called forced synchronous layout (or forced reflow).

Properties and methods that force layout include offsetTop/Left/Width/Height, clientWidth/Height, scrollTop/scrollHeight, getBoundingClientRect(), getComputedStyle() (for layout-dependent values), innerText, focus() (in some cases) and scrollIntoView().

Layout thrashing happens when you interleave writes and reads in a loop, forcing a layout on every iteration:

JavaScript
// ❌ Thrashing: write, read, write, read… → N forced layouts
for (const box of boxes) {
  box.style.width = `${box.parentElement.offsetWidth / 2}px`;   // read (forces layout) after the previous write
}

// ✅ Batch: all reads first, then all writes → 1 layout
const widths = boxes.map(b => b.parentElement.offsetWidth);
boxes.forEach((b, i) => { b.style.width = `${widths[i] / 2}px`; });

// ✅ Or schedule writes for the next frame (libraries like fastdom formalise read/write phases)
requestAnimationFrame(() => applyWrites());

DevTools' Performance panel marks forced reflows with a purple "Layout" block and a warning: "Forced reflow is a likely performance bottleneck". Chapter 27 shows how to find them.

Paint

Paint turns the layout tree into display lists: ordered drawing commands ("fill rect at x, y with colour", "draw text run", "draw image") for each layer, following the stacking order rules (chapter 14). Paint doesn't produce pixels yet. Turning commands into pixels is rasterisation, which happens later, mostly on the GPU, and in tiles.

Paint invalidation

When something changes visually, only the affected regions need repainting. Expensive-to-paint properties include big box-shadow and filter: blur() values on large areas, complex gradients, and large text shadows. Repainting them every frame (on hover across a list, say) shows up as long "Paint" and "Raster" events. DevTools' Rendering → Paint flashing highlights repainted areas in green, which is the quickest way to spot unnecessary repaints, such as a spinner that repaints the whole page.

Layers, the GPU and compositing

The page is divided into layers (in Chromium, composited layers and paint chunks). Each layer is rasterised into GPU textures in tiles, and the compositor combines the textures into the final frame, applying transforms, opacity, clipping and scroll offsets. The compositor runs on its own thread, separate from the main thread. That separation matters:

  • Scrolling is handled by the compositor: it just shifts already-rasterised tiles. That's why scrolling stays smooth while JavaScript is busy, unless a non-passive touchstart or wheel listener forces the compositor to wait for the main thread (chapter 17).
  • transform and opacity animations (CSS animations and transitions, the Web Animations API) can run on the compositor without involving the main thread.
  • Video, canvas (WebGL), and position: fixed elements often get their own layers.

What gets promoted to its own layer: 3D transforms, will-change: transform (or opacity), video and canvas, elements overlapping other composited layers (implicit promotion), and fixed elements during scrolling.

will-change is a hint to promote ahead of time so an animation starts smoothly. Don't apply it everywhere. Each layer costs GPU memory (width × height × 4 bytes, so a full-screen layer on a 4K display is about 33 MB), and too many layers (a "layer explosion") slow everything down. Apply it just before an animation and remove it afterwards, or reserve it for elements that animate constantly. DevTools' Layers panel shows layers and why each one was created.

main thread long task (JS) 300 ms compositor frames keep flowing: transform/opacity animations and scrolling stay smooth an animation of width/top/height needs the main thread → it freezes during the long task time →
Main thread versus compositor thread. A transform animation keeps running at 60 fps even while the main thread is blocked by a long task.

Frames and the frame budget

The display refreshes at 60 Hz (16.7 ms per frame), and at 90, 120 or 144 Hz on many phones and laptops (as little as 6.9 ms). To animate smoothly, everything the main thread must do per frame (input handlers, requestAnimationFrame callbacks, style, layout, paint) has to fit in the budget, with headroom for the browser's own work. A realistic target for your code is about 10 ms per frame at 60 Hz. Missing frames causes jank (visible stutter).

Chromium's frame pipeline per vsync: input events → rAF callbacks → style → layout → (ResizeObserver/IntersectionObserver) → paint → commit to the compositor → raster → draw. Visualise it in DevTools Performance with Frames and Main tracks. The newer Long Animation Frames API (LoAF) reports frames that took over 50 ms and attributes the time to specific scripts, which is the field-data counterpart of the long-task concept from chapter 15.

Rendering engines compared

Blink (Chromium) Gecko (Firefox) WebKit (Safari)
JS engine V8 (Ignition → Sparkplug → Maglev → TurboFan) SpiderMonkey (interpreter → Baseline → Warp/Ion) JavaScriptCore (LLInt → Baseline → DFG → FTL)
Style engine Blink style Stylo: parallel style calculation written in Rust (from Servo) WebCore
Rendering LayoutNG; compositor in the renderer, GPU process via Skia/Viz WebRender: GPU-first scene-graph renderer, written in Rust Core Animation-backed compositing
Process model Site isolation everywhere (desktop) Fission site isolation Process per tab, site isolation in progress

Firefox's Rust components (Stylo, WebRender) came from Servo, Mozilla's experimental parallel engine written in Rust. Servo now continues under the Linux Foundation, and Ladybird is a new independent engine written mostly from scratch. They show how memory safety (Vol. 1 ch. 2) and data-parallel design (Vol. 1 ch. 7) apply to browsers.

Inside the JavaScript engine

From source text to machine code

Every engine runs JavaScript through a pipeline of tiers, trading start-up speed for peak speed (Volume 1 chapter 10's interpreter-plus-JIT design). V8's, as of 2026:

Tier What it does Starts Speed of the code
Parser Turns source into an AST, lazily: inner functions are only pre-parsed until first called immediately —
Ignition Compiles the AST to compact bytecode and interprets it, collecting type feedback (which shapes and types each operation sees) first call slowest
Sparkplug Translates bytecode straight to machine code without optimising after a little use faster: no interpretation overhead
Maglev Mid-tier optimiser using the feedback; compiles fast warm functions much faster
TurboFan Full optimising compiler: inlining, escape analysis, speculative types hot functions fastest

Optimised code is speculative: if a function always saw objects of one shape (hidden class: the set and order of properties) and numbers that fit in 31 bits, TurboFan compiles exactly that case with a cheap check in front. When the check fails (a new shape, a string where numbers flowed), the engine deoptimises: it throws the optimised code away and falls back to the interpreter. Practical consequences for application code are modest but real: create objects with the same properties in the same order (constructors and object literals do this naturally), don't add or delete properties on hot objects, keep arrays homogeneous, and avoid passing wildly different types through one hot function. The bigger costs on real pages are usually parsing and compiling megabytes of JavaScript at start-up (chapter 27's bundle budgets) and long tasks, not micro-optimisation.

Memory and garbage collection

JavaScript memory is garbage-collected (Volume 1 chapter 10). V8's collector, Orinoco, is generational: most objects die young, so new objects go in a small young generation that is collected often by a fast parallel scavenger (copying survivors), and objects that survive two scavenges move to the old generation, collected by concurrent and incremental mark-compact that does most of its marking on helper threads while JavaScript keeps running. Pauses are usually a few milliseconds, but allocation-heavy code (creating thousands of temporary objects per frame) still causes jank. DOM nodes are managed together with JavaScript objects by Oilpan, Blink's C++ garbage collector, so a detached DOM tree stays alive as long as any JavaScript variable or listener references it: the classic single-page-app memory leak. DevTools' Memory panel finds them: take a heap snapshot, filter for "Detached".

Skipping work: containment and content-visibility

CSS containment

Invalidation is expensive because a change might affect anything: a box that grows pushes everything below it down. CSS containment lets you promise the browser that a subtree is independent, so it can limit work to that subtree:

CSS
.widget { contain: layout paint; }       /* its insides can't affect outside layout, and nothing paints outside its box */
.card   { contain: content; }            /* shorthand for layout + paint + style */
.panel  { contain: strict; }             /* content + size: its size doesn't depend on its children */

Container queries (chapter 14) rely on the same mechanism: container-type: inline-size applies inline-size containment so the container's width can't depend on its children.

content-visibility: rendering only what's on screen

content-visibility: auto goes further: the browser skips style, layout and paint for an element's contents while it's off-screen, and renders them just before they scroll into view. contain-intrinsic-size gives a placeholder size so the scrollbar stays sensible. Measured in Chromium 153 on a long article of 200 sections × 30 paragraphs:

CSS
section { content-visibility: auto; contain-intrinsic-size: auto 400px; }
Text
content-visibility: visible initial layout 75.4 ms | relayout after a window resize 29.5 ms
content-visibility: auto    initial layout  5.3 ms | relayout after a window resize  0.8 ms

A 14× faster first layout and 37× faster relayout from one CSS declaration, because only the few on-screen sections were laid out. (auto in contain-intrinsic-size makes the browser remember each section's real size once rendered.) It's ideal for long documents, feeds and chat histories; skipped content remains in the DOM, searchable with Ctrl+F and available to assistive technology. It became Baseline in 2024.

Lab: watching the engine work

These experiments read Chromium 153's own counters through the DevTools protocol (Performance.getMetrics, SystemInfo.getProcessInfo, Target.getTargets) while Playwright drove the page, plus a Node server's request log. They make the invisible parts of this chapter countable.

Experiment 1: which changes cost layout

A page of 300 boxes. Each change is applied to every box (or to one paragraph), then the test waits two animation frames and reads Chromium's cumulative RecalcStyleCount and LayoutCount:

JavaScript
const metrics = async () => (await cdp.send("Performance.getMetrics")).metrics;   // includes LayoutCount, RecalcStyleCount
await page.evaluate(change); await twoFrames(); // then compare counters
Text
width (geometry)                     style recalcs +1, layouts +1
background-color (paint only)        style recalcs +1, layouts +0
transform: none → translateX(5px)    style recalcs +1, layouts +1
transform again (5px → 20px)         style recalcs +1, layouts +0
opacity (composite only)             style recalcs +1, layouts +0
opacity again (0.5 → 0.8)            style recalcs +1, layouts +0
textContent of one <p>               style recalcs +1, layouts +1
add a class nothing matches          style recalcs +0, layouts +0

Mostly what the Start here table predicts, with two lessons the table hides:

  • The first transform cost a layout; changing it afterwards didn't. Going from transform: none to any transform creates a new stacking context and containing block for positioned descendants, which can change geometry. That's why animations should start from an existing transform (translateX(0)) or use will-change: transform set ahead of time, not switch from none on the first frame.
  • Adding a class that no selector uses cost nothing, not even a style recalculation: Blink's invalidation sets record which classes, ids and attributes any selector depends on, and skip changes no rule cares about. Changing text in one paragraph caused one (small) layout, because text size can change line breaks.

Experiment 2: how much a style change touches

20,000 cards; the stylesheet contains body.dark .card { background: #222; color: #eee }. Medians of six runs of Chromium's RecalcStyleDuration:

Text
toggle a class on <body> (affects 20,000 cards)   style 73.1 ms, layout 0.0 ms
toggle a class on one card                        style  0.1 ms, layout 0.0 ms

Toggling a class high in the tree invalidates every descendant that some selector might match through it, so the browser restyles all 20,000 cards: 73 ms, more than four frames, for a dark-mode switch. The same work scoped to one element is 700× cheaper. For theme switches, prefer custom properties on the root (:root.dark { --bg: #222 } with .card { background: var(--bg) }): it still restyles, but avoids selector matching across the tree, and keeps the change to one place. And keep the DOM small: style cost scales with the number of elements affected.

Experiment 3: the preload scanner

The page's <head> has a stylesheet and a script the server delays by one second. The body has an <img>, an image created by an inline script, and a CSS background image. The server logged each request's arrival time relative to the HTML request:

HTML
<head><link rel="stylesheet" href="/style.css"><script src="/slow.js"></script></head>
<body><h1>Menu</h1><img src="/dosa.png" alt="">
<script>const i = new Image(); i.src = "/from-js.png"; document.getElementById("later").append(i);</script>
<div style="background-image:url(/from-css-bg.png)"></div></body>
Text
   0 ms  GET /
  19 ms  GET /style.css
  20 ms  GET /slow.js
  20 ms  GET /dosa.png
1027 ms  GET /from-js.png
1030 ms  GET /from-css-bg.png

The parser was stuck at slow.js for a second, yet dosa.png was requested at 20 ms. That's the preload scanner: a second, lightweight parser that races ahead through the raw HTML looking for URLs in src, href and similar attributes, and requests them while the main parser is blocked. It can only find what's in the markup: the script-created image and the CSS background weren't discovered until the main parser and style calculation reached them, a full second later. This is why hero images belong in an <img> tag (not a CSS background or a JavaScript-rendered component), and why <link rel="preload"> exists for resources that can't be.

Experiment 4: processes and site isolation

Chromium launched with full site isolation (--site-per-process, the desktop default; test harnesses often disable it), with process types read from SystemInfo.getProcessInfo:

Text
start:                                           browser 1, GPU 1, network service 1
open localhost:8042/a                            browser 1, renderer 2, GPU 1, network 1
open 127.0.0.1:8042 in a second tab              browser 1, renderer 3, GPU 1, network 1
close the second tab                             browser 1, renderer 2, GPU 1, network 1
tab 1 embeds a 127.0.0.1 and a localhost iframe  browser 1, renderer 3, GPU 1, network 1
                                                 out-of-process iframes: [ 'http://127.0.0.1:8042/frame' ]

The first page brought up a renderer (plus a spare one Chromium keeps warm for the next navigation). A different site in a new tab got its own renderer, which went away with the tab. Most telling: of the two iframes added to tab 1, the same-site one (localhost) stayed in tab 1's process, while the cross-site one (127.0.0.1) became an out-of-process iframe, rendered by a separate sandboxed renderer and composited into the page. The page can't read that frame's memory, even with a Spectre-style attack (Volume 1 chapter 7). Site isolation costs memory (roughly 10–20% more in Chrome's measurements), which is why Android Chrome isolates only sites where users log in.

Try it yourself

  1. Repeat experiment 1 for box-shadow, filter: blur(), font-weight and visibility. Predict each before you run it.
  2. Record a theme switch on a real app in the Performance panel. How long is the "Recalculate Style" block, and how many elements did it touch (shown in the summary)?
  3. Move experiment 3's hero image into a CSS background, then fix the regression with <link rel="preload" as="image"> and measure again.
  4. Open chrome://process-internals (or Chrome's Task Manager, Shift+Esc) with several tabs and embedded third-party content. Which frames have their own processes?

Revision sheet: browser internals

Key ideas

  • URL → DNS → connection (TCP/QUIC) → TLS → HTTP → response → parse → DOM/CSSOM → style → layout → paint → composite; HSTS, the bfcache, service workers and speculation rules can short-circuit the start.
  • Processes: browser, network, GPU, storage, utility, and sandboxed renderers; IPC to the browser process for anything privileged; site isolation gives each site its own renderer, including out-of-process iframes.
  • Parsing: the tokenizer and tree builder build the DOM incrementally; the preload scanner fetches markup-discoverable resources early; CSS is render-blocking and blocks scripts that follow it.
  • Style: selector matching with invalidation sets; cost scales with affected elements; layout (LayoutNG) computes geometry with fragment trees; paint records display lists; raster and composite run off the main thread on the GPU.
  • Invalidation: geometry changes → layout + paint; visual changes → paint; transform/opacity on a composited layer → composite only; forced synchronous layout when script reads geometry after a write.
  • Layers: promoted for transforms, opacity animations, video, canvas, will-change, fixed elements; too many cost memory (layer explosion).
  • Frames: vsync-driven; the main thread must finish its part within the budget; the compositor can scroll and run transform/opacity animations independently.
  • JS engines: tiered (V8: Ignition, Sparkplug, Maglev, TurboFan), speculative, deoptimising; generational concurrent GC; Oilpan for DOM objects.
  • Skipping work: CSS containment, content-visibility: auto with contain-intrinsic-size, small DOMs.

Numbers to remember

  • Frame budget: 16.7 ms at 60 Hz, 8.3 ms at 120 Hz; long task over 50 ms.
  • In the lab: restyling 20,000 elements ≈ 73 ms; content-visibility: auto cut initial layout from 75 ms to 5 ms.
  • Site isolation memory overhead: roughly 10–20%.

Pitfalls

  • Animating top/left/width/height instead of transform; starting transforms from none mid-animation.
  • Toggling classes high in the tree for small visual changes on huge DOMs.
  • Hero images as CSS backgrounds or JS-inserted elements (invisible to the preload scanner).
  • will-change on everything (memory, layer explosion); leaving it on after the animation.
  • Detached DOM trees kept alive by listeners or caches.
  • Profiling only on a fast laptop; use CPU throttling and real mid-range phones.

Glossary

  • Main thread: the renderer thread running JavaScript, style, layout and paint recording.
  • Compositor thread: the thread that assembles layers into frames and handles scrolling.
  • Invalidation: marking work that must be redone after a change.
  • Out-of-process iframe (OOPIF): a cross-site frame rendered by a different renderer process.
  • Preload scanner: a look-ahead parser that discovers and requests resources early.
  • Deoptimisation: discarding speculative optimised code when its assumptions fail.