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

Workbench / Volume 2 Exercises: The Web Frontend

V2·18

Browser Internals

Exercises for Volume 2, chapter 18: the journey from URL to pixels, browser processes, sandboxing and site isolation, the rendering pipeline (parsing, style, layout and its invalidation, forced synchronous layout, paint and paint invalidation, layers, the GPU and compositing), frames and the frame budget, rendering engines compared, the JavaScript engine (from source to machine code, hidden classes and inline caches, memory and garbage collection), and skipping work with CSS containment and content-visibility. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.

32 exercises · ~13 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

Same four sets and the same locking. Browser internals are invisible until you measure them, so the programming exercises use the DevTools Performance panel, the Rendering drawer (paint flashing, layer borders, FPS meter), the Chrome DevTools Protocol's Performance.getMetrics (layout and style recalculation counts and durations, used here through Playwright), and Node for JavaScript-engine experiments. All outputs in the solutions are real: Chromium 153 and Node 22 (V8) on this book's 2-vCPU sandbox.

The chapter's lab already measured which property changes trigger layout, style invalidation scope, the preload scanner and the process model; these exercises add the frame budget, containment, content-visibility, object shapes and garbage collection, and connect them to Volume 1's architecture and runtime chapters.

Coverage map.

Chapter component Exercises
URL to pixels: the whole journey T1
processes, sandboxing, site isolation T2, P1
parsing, the preload scanner, style T3, P2
layout, invalidation, forced synchronous layout T4, P3
paint, paint invalidation, layers and compositing T5, P4
frames and the frame budget T6, P5
rendering engines compared T7
the JavaScript engine: tiers, hidden classes, inline caches T8, P6
memory and garbage collection in the engine T8, P7
containment and content-visibility T9, P8, P9

Theory

T1. From URL to pixels

Write the full sequence from typing tiffinbox.in/kitchens/42 and pressing Enter to the first pixels of the menu, naming the browser process or thread responsible for each step and the Volume 1 chapter it draws on: URL parsing and HSTS, DNS, TCP and TLS, the HTTP request, response streaming, the commit of the navigation to a renderer, parsing, the preload scanner, style, layout, paint, rasterisation, compositing, and display. Then mark which steps the JavaScript on the page can slow down.

T2. Processes, sandboxing and site isolation

  1. The chapter's lab counted processes: opening localhost in one tab and 127.0.0.1 in another created a second renderer; embedding iframes from both sites in one tab used one renderer per site. Explain site isolation and why it was rolled out after Spectre (Volume 1, chapter 07's T6).
  2. What does the renderer sandbox prevent (file system, network, devices, other processes), and what does that mean for the severity of a bug in the JavaScript engine?
  3. What are the costs of a process-per-site model (memory, process limits on low-end Android devices), and how do browsers adapt?

T3. Parsing and style

  1. Why can the HTML parser start building the DOM before the whole document has arrived, and how does the preload scanner speed up loading? Why did the lab's JavaScript-inserted image start 1 s later than the HTML-declared image?
  2. What does the style step compute, and why is style recalculation proportional to the number of elements affected? The lab toggled a class on <body> affecting 20,000 cards (73.1 ms) versus on one card (0.1 ms).
  3. Are complex selectors slow? Explain right-to-left selector matching and when selectors genuinely matter.

T4. Layout and forced synchronous layout

  1. What does layout compute, and why is it often the most expensive step? P3 measured 5,000 cards: initial layout 65.7 ms, and 40.5 ms again after a width change on <body>. Why does a width change force relayout of everything?
  2. Explain layout invalidation, dirty bits, and forced synchronous layout: which JavaScript reads force it, and why does interleaving reads and writes (the chapter 17 lab: 55 ms vs 1.9 ms) multiply it?
  3. Name three ways to reduce layout cost in a large page (fewer nodes, containment, avoiding layout-affecting animations, virtualisation).

T5. Paint, layers and compositing

  1. Explain paint, paint invalidation, raster and compositing. The lab showed that changing background-color triggers style and paint but no layout, opacity and a repeated transform change trigger neither layout nor paint (composite only), while the first transform triggered a layout. Explain the first-transform layout.
  2. What is a compositor layer, what promotes an element to one (will-change, 3D transforms, video, canvas, fixed positioning, animations of transform/opacity), and why can too many layers hurt (memory, layer explosion)?
  3. Why can a page scroll smoothly while the main thread is blocked (chapter 12's P11), and when does scrolling become janky anyway (non-passive wheel listeners, background-attachment: fixed, scroll-linked JS)?

T6. Frames and the frame budget

  1. P5 measured requestAnimationFrame intervals of 16.6–16.8 ms (60 Hz) and, with a 120 ms busy loop in one frame, one interval of 117 ms. Explain the frame budget at 60, 90 and 120 Hz, what runs in one frame (input, rAF, style, layout, paint, composite), and how many frames the 120 ms task dropped.
  2. Why do users notice a dropped frame during an animation or scroll more than during idle time, and what are the RAIL-style targets (response under 100 ms, animation frames under 16 ms, idle work in 50 ms chunks, load)?
  3. What does the Long Animation Frames API (LoAF) add over long tasks for diagnosing jank and INP?

T7. Rendering engines compared

Compare Blink (Chrome, Edge, Opera, Samsung Internet, Android WebView), Gecko (Firefox) and WebKit (Safari, and every browser on iOS), and their JavaScript engines (V8, SpiderMonkey, JavaScriptCore). Why does "every iOS browser uses WebKit" matter for TiffinBox's testing strategy and feature choices? Mention notable architectural differences (Firefox's WebRender and Stylo from Servo, WebKit's process model) only as far as they affect developers.

T8. Inside the JavaScript engine

  1. Describe V8's pipeline: parsing (lazy parsing and pre-parsing), the Ignition interpreter, the Sparkplug baseline compiler, Maglev and TurboFan optimising compilers, and deoptimisation. Connect it to Volume 1, chapter 10's JIT tiers in HotSpot.
  2. P6 summed price over 2 million objects in separate Node processes: objects of one shape 5.5–6.1 ms, of four shapes 4.7 ms, of eight shapes about 24 ms. Explain hidden classes (maps/shapes), inline caches and the polymorphic-to-megamorphic transition, and what coding habits keep objects monomorphic.
  3. P7 allocated 3 million small objects in 504 ms; --trace-gc showed 85 Scavenge collections and 2 Mark-Compact. Explain V8's generational GC (young generation scavenger, old generation mark-compact, concurrent and incremental marking) and its effect on frame drops, in Volume 1, chapter 10's terms.
  4. Why does shipping 1 MB of JavaScript cost a low-end phone more than downloading 1 MB of images?

T9. Containment and content-visibility

  1. What do contain: layout, paint, size, style and the shorthands content and strict promise the browser, and what does each let it skip?
  2. P8 rendered 5,000 cards: initial layout 65.7 ms without and 10.2 ms with content-visibility: auto; contain-intrinsic-size: auto 120px; relayout after a width change 40.5 ms versus 5.7 ms. Explain how content-visibility: auto works, why contain-intrinsic-size (with auto) matters for the scrollbar and layout shifts, and its accessibility and find-in-page behaviour.
  3. When is content-visibility the wrong tool, compared with list virtualisation?

Programming exercises

P1. See the process model

Open chrome://process-internals (or Chrome's Task Manager, Shift+Esc) and record processes as you: open one site, open a second site in another tab, open a page that embeds a cross-site iframe (chapter 12's P7 setup), and close tabs. Then crash a renderer with chrome://crash in one tab and observe what survives. Compare with the chapter's lab counts.

P2. The preload scanner and discoverability

Serve a page with a CSS file, a classic blocking script (served with a 1-second delay), a <img> in the HTML, and an image created by JavaScript inside the slow script. Log the server's request times. Then add <link rel="preload" as="image" href="/from-js.png"> and compare. Finally, inline a large <style> in the head and see how it affects first paint versus an external stylesheet.

P3. Measure layout and the cost of a width change

Using Playwright and the CDP Performance.getMetrics method (or the Performance panel's Layout events), render 5,000 cards and record LayoutDuration and RecalcStyleDuration for the initial render, and for a width change on <body> (document.body.style.width = '600px' followed by a geometry read). Then repeat the width change with contain: layout on each card, and with content-visibility: auto.

P4. Paint, layers and composite-only animation

With DevTools' Rendering drawer, enable Paint flashing and Layer borders. Animate a card's left from 0 to 300 px, then its transform: translateX(), then its background-color, and note which flash (repaint) and whether a layer border appears. Then add will-change: transform to 500 list items and check the Layers panel's memory estimate. Finally, record the Performance panel for each animation under 6× CPU throttling while a busy loop runs on the main thread.

P5. The frame budget, measured

Measure 60 requestAnimationFrame intervals on an idle page (min, average, max). Then run a 120 ms busy loop inside one rAF callback and print all intervals. If you have a 90 or 120 Hz device, repeat there. Then add a CSS animation and a transform animation and run the same busy loop to see which keeps moving.

P6. Object shapes and inline caches

In Node, create 2 million objects in three ways (one shape; four shapes with properties in different orders; eight shapes with varying numbers of extra properties), each in a separate process, and time summing one property over all of them (best of 10). Then run the eight-shape version with --trace-deopt or --trace-ic (if your Node build supports it) to see the megamorphic site. Rewrite the object creation to use one constructor with all fields, and time again.

P7. Garbage collection in V8

Run a Node script that allocates 3 million small objects ({i, s: 'order-' + i}) and push them into an array, with node --trace-gc. Count Scavenge and Mark-Compact events and their pause times. Then change it to allocate 3 million temporary objects that are dropped immediately (summing a field), and compare. In the browser, record a Performance profile of an animation that allocates a new array every frame, and look for GC events (minor GC) in frames.

P8. content-visibility on a long menu

Apply content-visibility: auto with contain-intrinsic-size: auto 120px to each dish card on a 5,000-card page. Measure initial layout and style time (P3's method), scrolling smoothness with the FPS meter under 6× throttling, the scrollbar behaviour (does it jump?), find-in-page for a dish near the bottom, and screen-reader navigation by headings. Then remove contain-intrinsic-size and watch the scrollbar.

P9. Containment for an independently updating widget

Build a page with a large article and a "live order status" widget in the sidebar that updates its text every 500 ms. Record the Performance panel: how much of the page is relaid out on each update? Add contain: layout paint (or contain: content) and a fixed size to the widget, and record again. Then make the widget grow when a long status message arrives and observe what containment does to overflowing content.

Cumulative projects (chapters so far: Volume 1, and Volume 2's 00, 12–18)

C1. A performance investigation report for one page

Take the TiffinBox menu page you've built across chapters 13–17 (or a real food-delivery site) and write a browser-internals performance report: a Performance-panel recording of load and of three interactions (filter, add to cart, scroll) at 6× CPU throttling; for each long frame, the breakdown into script, style, layout, paint and composite with attribution (LoAF); the number of nodes, layers and forced layouts; JavaScript parse/compile time; GC events; and a ranked list of fixes with expected gains, then implement the top three and re-measure.

Combines: measurement discipline (Vol 1 ch 01–07); caches and the memory hierarchy (ch 07); processes and scheduling (ch 08); networking (ch 09); JIT and GC (ch 10); this volume's loading (ch 12), HTML and CSS (ch 13–14), JavaScript (ch 15) and DOM (ch 17), all seen through this chapter's pipeline.

C2. A smooth, accessible drag-to-reorder list

Build "reorder your favourite dishes" with pointer events: drag a card, other cards make room with animated transitions, keyboard reordering (select with Space, move with arrow keys, announce positions in a live region), touch support, and auto-scroll near the edges. Keep every frame under budget at 6× throttling: animate only transform, measure positions once at drag start (FLIP technique), use requestAnimationFrame for updates, touch-action: none on handles, pointer capture, and no layout reads during the drag.

Combines: data structures for ordering (Vol 1 ch 03); algorithms for insertion position (ch 04); frame budgets and compositing (ch 07's hardware view and this chapter); events and pointer capture (ch 17); accessibility tree and live regions (ch 12, 13); CSS transforms (ch 14).

C3. Explain one frame of your app, end to end

Pick one interaction in your app (tapping "Add to cart" on a phone) and write a document that explains everything that happens from the finger touching the glass to the updated badge appearing on screen, across hardware (touch controller, interrupts: Volume 1, chapter 07–08), the OS (input events to the browser process), the browser (IPC to the renderer, hit testing on the compositor, the main thread event dispatch), your JavaScript (event handler, state update, DOM change), rendering (style, layout, paint, raster, composite) and display (vsync), with timings from a Performance recording where measurable.

Combines: everything in Volume 1 (interrupts, scheduling, IPC, caches, JIT) and Volume 2 so far.

What the chapter leaves out

Fonts, text shaping and their rendering cost

Text is the most expensive thing most pages lay out: font loading (each family and weight a file; font-display behaviour; layout shifts when the web font replaces the fallback: chapter 14's gaps), shaping (HarfBuzz converts characters to positioned glyphs; complex scripts such as Devanagari, Telugu and Arabic need contextual forms and reordering), line breaking (ICU rules, hyphenation by language), and fallback across fonts for characters a font lacks (emoji, ₹ in old fonts). Pages with lots of Indic text or many font weights spend measurable layout time here; subsetting, unicode-range, fewer weights (variable fonts) and size-adjusted fallbacks help.

Images and video decoding pipelines

Images go through download, decode (often off the main thread; decoding="async" and img.decode() give control), possible resizing, upload to the GPU, and raster. Very large images cost memory (a 4000 × 3000 photo decoded is 48 MB regardless of its compressed size) and can cause jank when decoded on demand during scrolling; serve appropriately sized images (chapter 13's T5) and modern formats. Video uses hardware decoders and its own compositor layers; autoplaying many videos in a feed is a battery and memory problem on phones.

Back/forward cache, prerendering and speculation rules

The fastest navigation is one that's already done: the bfcache (chapter 12's T6) restores pages instantly on Back/Forward; prefetch and prerender (now via the Speculation Rules API, <script type="speculationrules"> with URL patterns and eagerness levels) let the browser load or fully render likely next pages in the background, so navigation appears instant. Costs: wasted bandwidth and server load for unused prerenders, analytics double counting (use document.prerendering and prerenderingchange), and side effects on GET requests (another reason GETs must be safe). For TiffinBox, prerendering the kitchen page when a user hovers or touches a kitchen card can make browsing feel instant.

The GPU process, WebGL and WebGPU

The GPU process owns the graphics driver connection (isolated because drivers crash and are a security risk), rasterises tiles, composites layers and runs WebGL and WebGPU (a modern, lower-level API for graphics and compute in the browser, now shipping in major browsers). WebGPU enables in-browser ML inference, image processing and data visualisation at scales canvas can't reach. Most product UIs never touch it directly, but maps (Mapbox, Google Maps vector rendering) and charts libraries do, and their performance depends on GPU memory and driver quality on low-end devices.

Browser engineering as a field

To go deeper: the "Inside look at modern web browser" series (Chrome developers), "Life of a Pixel" (Chromium's rendering walkthrough), the WebKit and Mozilla engineering blogs, the Web Browser Engineering book (browser.engineering, building a toy browser in Python: the best way to internalise this chapter), and Servo and Ladybird as readable modern engine codebases. Reading the HTML, CSS and DOM specifications' processing models (the event loop, rendering update steps) explains many "weird" behaviours precisely.

Senior exercises

S1. Diagnose jank that only happens on low-end phones

Users on budget Android phones report that the menu page "freezes for a second" when they open the filters panel, and scrolling stutters afterwards; on developers' laptops it's smooth. Plan the investigation (real devices, remote debugging, field data), the likely causes from this chapter, and the fixes, with how you'd confirm each.

S2. Review a design for an animated dashboard

A designer's prototype for the kitchen dashboard has: a full-screen animated gradient background, glassmorphism panels with backdrop-filter: blur(20px), 40 order cards each with a pulsing box-shadow animation, a ticker that scrolls text by animating left, and charts that re-render every second. The tablets in kitchens are three-year-old low-end Android devices. Write the review from a rendering-cost perspective, with alternatives that keep the design's intent.

S3. Decide on a performance budget per device class

Write TiffinBox's frontend performance budget for three device classes (low-end Android, mid-range Android, iPhone/desktop): maximum JavaScript (compressed and main-thread time), DOM size, layers, LCP, INP and CLS targets, frame budget for animations, and how each is measured in CI and in the field. Justify the numbers with this chapter's mechanisms.

S4. Explain to a backend team why the frontend is "slow"

The backend team has made the menu API respond in 40 ms at p99, but product still says the menu page is slow. Write a short, evidence-based explanation (under 300 words) of where the remaining time goes, using a Performance recording's numbers, and propose how both teams can help (including backend changes that make the frontend faster).

S5. Teach "the pipeline" with a single diagram and three rules

Create the outline of a one-page explainer for product engineers: one diagram of the pipeline (input → JS → style → layout → paint → composite → display, with main thread vs compositor/GPU marked), a table of common CSS properties and which stages they trigger, and three rules for writing fast UI code. Say how you'd make it stick (where it lives, how it's referenced in reviews).