Volume 2 Companion: The Web FrontendPractice for Volume 2
0 / 0

Workbench / Volume 2 Companion: The Web Frontend

V2·18

Browser Internals

Companion to Volume 2, chapter 18: how loading, the rendering pipeline and the engine connect; new angles (the pipeline as a print shop, invalidation as a dirty-dishes list, compositing as transparencies on an overhead projector, the frame budget as a train timetable); what the chapter simplifies, measured in Chromium: a late web font that moves the Order button 91 px, two "fixes" that made it worse and one that brought layout shift to 0.000; a `:has()` rule that makes every class change on a 3,000-card page 45 times more expensive; speculation rules that a strict CSP silently refuses inline but accepts as a header; the theory behind it; how Google's `web-vitals` computes CLS (and why ten small shifts score 0.029, not 0.291); four debugging drills; interview questions with how to approach each.

6 sections · ~15 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 18 has three strands. From URL to pixels: navigation and loading, the browser's processes, sandboxing and site isolation, parsing and the preload scanner. The rendering pipeline: style, layout, paint, layers and compositing, frames and the frame budget, and what invalidates each stage (including forced synchronous layout). The engine and skipping work: JavaScript compilation tiers, object shapes and inline caches, garbage collection, CSS containment and content-visibility, and how to measure all of it.

from URL to pixels the rendering pipeline the engine, and skipping work navigation, loading DNS · TLS · bytes processes browser · renderer · GPU sandboxing least privilege site isolation a process per site parsing tokens · tree · scripts preload scanner finds resources early style which rules apply layout boxes and positions paint drawing commands layers, compositing GPU puts it together frames 16.7 ms at 60 Hz invalidation, forced layout read after write compilation tiers interpreter → optimiser shapes, inline caches same keys, same order garbage collection young and old containment limit invalidation content-visibility skip off-screen work measuring traces · observers handled by in a plus then helped by feeds feeds then within broken by relies on plus and extended by proved by goes deeper: ch12 the browser · ch14 CSS · ch15 the event loop · ch27 performance budgets · ch32 real-user monitoring exercises: P1–P9 processes, preload scanner, layout cost, layers, frame budget, shapes, GC, content-visibility, containment
Concept map of chapter 18, browser internals: from URL to pixels (navigation and loading, processes and sandboxing, site isolation, parsing and the preload scanner), the rendering pipeline (style, layout, paint, layers and compositing, frames and the frame budget, invalidation and forced layout) and the engine and skipping work (JavaScript compilation tiers, object shapes and inline caches, garbage collection, containment, content-visibility), with links such as a style change invalidating layout and paint, and a forced read making the browser do that work at once.

The links worth remembering:

  • Every change starts a chain. A class change invalidates style; a style change may invalidate layout, then paint, then compositing. How far the chain goes decides the cost, which is why transform and opacity animations are cheap and width animations aren't.
  • Reading forces the chain to run now. The browser batches work until the next frame unless you read a layout value (offsetHeight, getBoundingClientRect, getComputedStyle) in between: then it must finish the work immediately.
  • The cheapest work is work that's skipped. Containment, content-visibility, compositor-only animation and narrow selectors all exist to keep invalidation small (Gaps 2).

Explain it differently

1. The rendering pipeline is a print shop. The editor decides which styles apply to each paragraph (style), the typesetter places every line and box (layout), the printer turns layouts into ink (paint), and the binder stacks pre-printed sheets in the right order (compositing). Changing a word's colour needs only the printer; changing a column width needs the typesetter again, and everything after.

2. Invalidation is the dirty-dishes list. The browser doesn't redo work immediately when you change something; it writes "this table needs clearing" on a list and does the whole list once per frame. Forced layout is a customer asking "is table 4 clean yet?": the staff must stop and clear it right now, and if you ask after every change, nothing gets batched.

3. Compositing is transparencies on an overhead projector. Each layer is a sheet already drawn. Moving a sheet (transform) or making it fainter (opacity) doesn't need anyone to redraw it; changing what's on a sheet (its text, its size) does. Too many sheets, though, and the projector runs out of room (memory).

4. The frame budget is a train timetable. At 60 Hz a train leaves every 16.7 ms. Anything not ready when the train leaves waits for the next one; a task that takes 50 ms makes three trains leave empty, and users see a stutter.

5. The preload scanner is a waiter reading ahead in the order. While the kitchen (the parser) is stuck on a blocking script, the waiter skims the rest of the order (HTML) and starts fetching ingredients (images, stylesheets, scripts) it can see. Resources it can't see in the HTML (injected by script, hidden in CSS) aren't fetched early.

6. Hidden classes are labelled shelves. V8 gives objects with the same keys in the same order the same shelf layout, so code can reach for "the third slot" without searching. Objects built in different orders, or with keys deleted, get different layouts, and code that sees many layouts has to search every time (Chapter Exercises P6).

7. Site isolation is separate kitchens per restaurant. Since Spectre, pages from different sites run in different processes, so one site's code can't read another's memory even through CPU side channels. It costs memory, which is why the browser keeps same-site pages together.

8. CLS is a complaint log with sessions, not a running total. A page that shifts a little now and then over an hour isn't as bad as one that jumps badly once. The metric groups shifts into bursts and reports the worst burst (Code walkthrough).

Gaps and misconceptions

What the chapter oversimplifies

All outputs are real, from Chromium 153 through Playwright, with small local servers (exp/18).

1. Fonts: the late web font moves the page, and the obvious fixes can make it worse. A heading and two paragraphs in a web font that arrives 1.5 s late, with an Arial fallback; the position of the "Order" button before and after the font arrives, and the page's cumulative layout shift (CLS):

Terminal
swap                             CLS 0.031 | font face status: loaded | button y before the font: 364, after: 455
optional                         CLS 0.000 | font face status: loaded | button y before the font: 364, after: 364
swap, overrides on the web font  CLS 0.101 | font face status: loaded | button y before the font: 364, after: 517
swap, adjusted fallback          CLS 0.000 | font face status: loaded,loaded | button y before the font: 455, after: 455

With font-display: swap, text appears at once in Arial and reflows when the font arrives: the button jumps 91 px, just as a user might be tapping it. optional never shifts, because a font that misses the first ~100 ms isn't used on that page view at all (it's cached for the next one). The third line was my first fix: size-adjust and ascent-override on the web font, which changed the web font's own metrics and tripled the shift. The right place is a fallback face: @font-face { font-family: BrandFallback; src: local("Liberation Sans"), local("Arial"); size-adjust: 125.4%; ascent-override: 74%; descent-override: 18.8%; … }, sized to the web font's measured width (canvas measureText: 4,804.8 px against 3,831.3 px, so 125.4%). The second attempt used the web font's vertical metrics directly (92.8% and 23.6%) and scored 0.070, because size-adjust scales the overrides too; dividing them by 1.254 gave the last line: the button doesn't move at all. Font metric matching is measurable, and worth measuring (drill D1).

2. Selectors have a cost when things change: :has() turns a local change into a page-wide one. The chapter shows style as "which rules apply". What it costs depends on what a change can affect. Toggling a class on one of 3,000 cards and reading its style, with different :has() rules on the page:

Terminal
no :has()                        toggle one card's class, then read its style: 5 µs per change (median of 5 runs of 500)
body:has(#tickets) > main        toggle one card's class, then read its style: 6 µs per change (median of 5 runs of 500)
body:has(.ticket.late) > main    toggle one card's class, then read its style: 229 µs per change (median of 5 runs of 500)
main:has(> .tickets)  [scoped]   toggle one card's class, then read its style: 5 µs per change (median of 5 runs of 500)

body:has(.ticket.late) makes every late toggle a question about body, whose answer changes main's style, so the browser recomputes styles far beyond the card: 45 times the cost. A :has() whose argument never changes (#tickets, as the stage 17 display uses), or one scoped to a direct child, costs nothing measurable. On a kitchen display that updates 200 cards every 15 seconds, 229 µs per change is 46 ms of style work per tick: a dropped frame each time (drill D2). Use :has() with stable arguments, or on small subtrees; for state that changes often, set a class on the ancestor from script.

3. Speculation rules and a strict Content Security Policy. Chrome can prerender the next page a user is likely to visit, using speculation rules (Chapter Exercises leaves them out). Under stage 12's CSP (script-src 'self'), the usual inline form is refused, and the header form works:

Terminal
/inline  requests after load: [('/inline', None)] | console errors: ["Applying inline speculation rules violates the following Content Security Policy directive 'script-src 'self''"]
/header  requests after load: [('/header', None), ('/rules.json', None), ('/menu', 'prefetch;prerender')] | console errors: []

The inline <script type="speculationrules"> needs 'inline-speculation-rules' (or a hash) in script-src; the Speculation-Rules: "/rules.json" response header loads rules from a same-origin file instead. The prerender request arrives with Sec-Purpose: prefetch;prerender, which the server should treat as "not a visit yet": no analytics, no side effects. Prerendered pages also run their scripts before the user arrives, which is only safe for pages whose GETs change nothing (stage 13's rule) (drill D3).

4. Measuring layout shift: "the sum of shifts" isn't CLS. The experiment in Gaps 1 sums layout-shift entries, which is right for one page load. For a page open for hours, it isn't: see the Code walkthrough.

Common misconceptions

Misconception What's actually true Where it's shown
"font-display: swap is the safe default." It shows text early and shifts the layout when the font arrives. Gaps 1; drill D1
"size-adjust on the web font fixes font shifts." It belongs on a local fallback face, with overrides divided by the adjustment. Gaps 1
"Selector cost is about matching speed." It's about how much a change invalidates; a :has() on a changing class reaches the whole page. Gaps 2; drill D2
"Speculation rules are just markup." Inline rules are script for CSP; use the header under a strict policy. Gaps 3; drill D3
"CLS adds up every shift." It's the worst burst (session window) of shifts. Code walkthrough
"Fast servers mean fast pages." Most load time is in the browser: parsing, fonts, images, scripts and rendering. Chapter Exercises S4

Theoretical gaps: the ideas behind the chapter

1. Rendering is incremental computation. The browser keeps the results of each stage (computed styles, layout boxes, paint records, layers) and recomputes only what a change invalidates, like a spreadsheet recomputing dependent cells. Performance work is mostly about keeping the dependency set of a change small: containment declares boundaries, content-visibility skips subtrees, and selectors like :has() widen dependencies (Gaps 2).

2. Pipelines trade latency for throughput, and frames are the deadline. Splitting rendering into stages lets them run on different threads (main thread, compositor, raster, GPU), so a smooth scroll can continue while the main thread is busy. The cost is coordination: anything that needs the main thread waits for it, and a frame missed is a frame missed. It's the same trade-off as CPU pipelines (Volume 1) and the order processing stages of Volume 3.

3. Text layout is a hard problem the browser hides. Turning characters into positioned glyphs (shaping) handles ligatures, combining marks, right-to-left runs, Indic conjuncts and line breaking rules per language, using HarfBuzz in Chromium and Firefox. Fonts carry the metrics (ascent, descent, advance widths) that decide line heights and wrapping, which is why swapping fonts moves the page and why metric overrides can stop it (Gaps 1).

4. User-centric metrics measure perception, not mechanism. LCP (when the main content appears), INP (how fast the page responds to input) and CLS (how much it jumps) were chosen because they correlate with user experience, and each has careful rules (largest element, worst interactions, session windows) to make it robust. Optimising a metric's mechanism instead of the experience (hiding content until load to avoid shifts) satisfies the number and fails the user.

5. Speculation trades resources for latency. Prefetching and prerendering spend bandwidth, CPU and server capacity on pages the user may never open, to make the likely next page instant. The right amount depends on how sure you are (hover, viewport, past behaviour) and what it costs (mobile data, server load). The server must be able to tell speculation from intent (Sec-Purpose), the same way it must tell retries from new requests (stage 5).

6. Browsers are designed for hostile content. Process isolation, sandboxing, site isolation and CSP exist because the browser runs code from anyone. Many rendering decisions (cross-origin images can't be read from a canvas, timers are coarsened, performance.now() resolution is reduced) are security decisions with performance consequences, which is why measurements inside the page have limited precision (the experiment in Gaps 2 had to repeat each change 500 times).

Applying it

Code walkthrough

CLS, LCP and INP are defined by the Web Vitals programme, and Google's web-vitals library is the reference implementation most real-user monitoring uses. Excerpts from version 4.2.4, dist/modules/onCLS.js, installed from npm.

Session windows

JavaScript
        const handleEntries = (entries) => {
            entries.forEach((entry) => {
                // Only count layout shifts without recent user input.
                if (!entry.hadRecentInput) {
                    const firstSessionEntry = sessionEntries[0];
                    const lastSessionEntry = sessionEntries[sessionEntries.length - 1];
                    // If the entry occurred less than 1 second after the previous entry
                    // and less than 5 seconds after the first entry in the session,
                    // include the entry in the current session. Otherwise, start a new
                    // session.
                    if (sessionValue &&
                        entry.startTime - lastSessionEntry.startTime < 1000 &&
                        entry.startTime - firstSessionEntry.startTime < 5000) {
                        sessionValue += entry.value;
                        sessionEntries.push(entry);
                    }
                    else {
                        sessionValue = entry.value;
                        sessionEntries = [entry];
                    }
                }
            });
            // If the current session value is larger than the current CLS value,
            // update CLS and the entries contributing to it.
            if (sessionValue > metric.value) {
                metric.value = sessionValue;
                metric.entries = sessionEntries;
                report();
            }
        };

Shifts are grouped into sessions: a shift joins the current session if it's less than 1 s after the previous shift and less than 5 s after the session's first; otherwise it starts a new one. CLS is the largest session, not the sum. Shifts within 500 ms of user input (hadRecentInput) don't count, because content moving in response to a tap is expected. The entries of the worst session are kept, so a report can say which elements moved.

When to report

JavaScript
        const po = observe('layout-shift', handleEntries);
        if (po) {
            report = bindReporter(onReport, metric, CLSThresholds, opts.reportAllChanges);
            onHidden(() => {
                handleEntries(po.takeRecords());
                report(true);
            });
            // Only report after a bfcache restore if the `PerformanceObserver`
            // successfully registered.
            onBFCacheRestore(() => {
                sessionValue = 0;
                metric = initMetric('CLS', 0);
                ...

CLS can grow for as long as the page is open, so there's no "done" moment. The library reports when the page becomes hidden (visibilitychange), the last moment a browser reliably runs code (mobile browsers may kill a backgrounded page without unload), after flushing pending entries with takeRecords(). A page restored from the back/forward cache is a new page view from the user's point of view, so the metric starts again. And the whole thing waits for the first contentful paint (onFCP wraps it, "to match the current behavior of CrUX"), because shifts before anything is visible don't affect anyone.

Read it yourself

  1. A kitchen display, open all day, inserts a 20 px "New order!" banner at the top every few minutes. What does a naive sum of shifts report after ten banners, and what does onCLS report?
  2. Why does the library report on visibilitychange to hidden, and not on unload or beforeunload?

Debugging drills

D1. Customers tap the wrong button on the menu page

After a rebrand that added a custom web font, support reports customers adding the wrong dish: "I pressed Add on Idli and got Pongal". It happens mostly on the first visit, on mobile data. The CSS: @font-face { font-family: Brand; src: url(/fonts/brand.woff2); font-display: swap; } and body { font-family: Brand, Arial, sans-serif; }.

D2. The kitchen display stutters every 15 seconds

The display (stage 17) refreshes ages every 15 seconds, toggling a late class on cards. With 200 open orders on a mid-range tablet, the Performance panel shows a 40–60 ms "Recalculate Style" every 15 seconds; scrolling stutters then. A designer recently added body:has(.ticket.late) .summary { color: var(--danger); } to turn the summary bar red when any order is late.

D3. Analytics counts menu visits that never happened

After enabling speculation rules (prerendering /menu from the home page) through the Speculation-Rules header, the analytics dashboard shows menu visits up 60%, but orders are flat and the menu's bounce rate jumped. A developer had first tried the inline form, which "didn't work", before switching to the header.

D4. The performance dashboard says the kitchen display gets worse all day

A real-user monitoring dashboard computes CLS as the sum of all layout-shift entries, sent when the page unloads. The kitchen display's "CLS" is 0.05 at 9:00 and 2.4 by 15:00; managers want the front-end team to fix "the regression". Some displays report nothing at all.

Career-oriented

Interview prep

Mid level

Q1. Animate a toast sliding in from the bottom. Which properties do you animate, and why?

How to get there. Walk the pipeline: which stages does each candidate property invalidate? Then mention accessibility (reduced motion) and how you'd verify.

Q2. A page's LCP is 4.5 s on mobile. Walk through how you'd find out why.

How to get there. LCP is one element's render time. Find which element it is, then break its time into parts: server response, resource discovery, resource loading, and render delay. Each part has different fixes.

Senior level

Q3. The kitchen display must stay smooth with 500 open orders on a cheap tablet. What do you design in from the start?

How to get there. Work through the pipeline for the display's three activities: the first render (a snapshot), single updates (an event), and periodic updates (ages every 15 s). For each, keep invalidation local and avoid forced layout.

Q4. The marketing team wants a custom brand font on every page. What's your position, and what do you require?

How to get there. Weigh brand value against measurable costs (bytes, LCP, CLS, rendering for Indic scripts), and turn your position into requirements the team can meet. Chapter Exercises leaves fonts out.

Staff level

Q5. Should TiffinBox use speculation rules to prerender likely next pages? Make the decision.

How to get there. Chapter Exercises leaves speculation rules out. Weigh latency gains against costs (server load, data use, analytics and side effects), consider which pages are safe, and define how to roll it out and measure.

Q6. Your organisation's apps are used in Chrome, Edge and Safari on iPads, on very old hardware in some customer sites. How do you set performance expectations across browsers and devices?

How to get there. Chapter Exercises S3 sets budgets per device class. This is about engine differences: which APIs and behaviours differ (Safari's WebKit, no speculation rules, different font loading), and how to make decisions without testing everything everywhere.