Workbench / Volume 2 Exercises: The Web Frontend
V2·27
Frontend Performance
Exercises for Volume 2, chapter 27: why performance matters and how it's measured (lab vs field data), the Core Web Vitals (LCP, INP, CLS) and FCP/TTFB; JavaScript cost (long tasks, bundle size, code splitting, tree shaking, lazy loading, prefetching); assets (images, fonts, CDN caching); and runtime performance (virtualisation, memory leaks, worker offloading, performance tools). 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.
Start here: how this chapter's exercises work
Same four sets and the same locking. The measured exercises use Chromium 153 through Playwright, its PerformanceObserver entries (layout-shift, long-animation-frame), esbuild 0.25 for bundle sizes, and real npm packages (lodash 4.18, lodash-es, moment 2.31, date-fns 4.4). Every quoted output is real. Four of them are useful surprises:
- P2: a font fallback with guessed size-adjust values still shifted the layout, while one whose
local()font didn't exist made CLS worse (0.195 against 0.133 with no adjustment). - P4:
import { debounce } from 'lodash'pulled in 72 KB, against 2.9 KB from lodash-es. - P6: moving a filter of 300,000 objects to a Web Worker made it slower overall, because copying the data blocked the main thread for 90 ms.
- P7: the Long Animation Frames API named the third-party script responsible for a slow click.
The chapter's lab fixed a slow page (LCP 10,904 → 172 ms, 11.5 MB → 89 KB), measured INP's three phases (256 ms with all work in the handler, under 16 ms after deferring or yielding), compared eager, lazy and prefetched code splitting (page ready in 1,369 / 183 / 189 ms), and found a memory leak growing by 10,000 DOM nodes per visit. The exercises build on those.
Coverage map.
| Chapter component | Exercises |
|---|---|
| why performance matters; lab vs field data | T1, P9 |
| Core Web Vitals; LCP | T2, P1 |
| INP | T3, P7 |
| CLS | T4, P2 |
| FCP and TTFB | T2 |
| long tasks | T3, P7 |
| JS bundle size, code splitting, tree shaking | T5, P4 |
| lazy loading and prefetching | T5, P3 |
| image optimisation | T6, P1 |
| font optimisation | T6, P2 |
| CDN caching | T6 |
| virtualisation | T7, P5 |
| memory leaks | T7, P8 |
| worker offloading | T8, P6 |
| performance tools | T9, P7, P9 |
Theory
T1. Why performance matters, and lab vs field data
- Give the business and user reasons for speed (conversion, bounce, SEO ranking signals, data costs on prepaid plans, battery, accessibility for people on low-end devices), and why "fast on my MacBook on office Wi-Fi" says little about TiffinBox's users on budget Android phones over 4G.
- Explain lab data (Lighthouse, WebPageTest, DevTools, Playwright: controlled, reproducible, for debugging) and field data (RUM via
web-vitals, the Chrome UX Report: real users, real devices, percentiles). Why are Core Web Vitals judged at the 75th percentile of field data, and why can a page pass Lighthouse but fail in the field (and the reverse)? - Chapter 26's P7 measured 16–22% run-to-run variance in lab LCP. How do you use lab tests responsibly (medians, throttling, comparing branches) and what questions can only field data answer?
T2. Core Web Vitals, LCP, FCP and TTFB
- State the thresholds: LCP ≤ 2.5 s, INP ≤ 200 ms, CLS ≤ 0.1 (good), and what each measures. What are FCP and TTFB, and why are they diagnostic rather than Core Web Vitals?
- Break LCP into its four sub-parts (TTFB, resource load delay, resource load duration, element render delay) and, for the lab's slow page (LCP 10,904 ms with an 11.8 MB PNG found late at low priority), say which sub-part each fix addressed.
- What can be the LCP element (images,
<image>in SVG, video posters, background images via CSS, block-level text), and why are a CSS background or a JavaScript-inserted hero image common LCP problems (chapter 18's preload scanner)?
T3. INP and long tasks
- Explain INP's three phases (input delay, processing time, presentation delay) using the lab's numbers (256 ms: input 3, processing 250, presentation 3), and the common cause of each phase being long.
- The lab's two fixes (update the UI first and defer the rest; split work with
scheduler.yield()) both brought the interaction under 16 ms. Why does a single deferred 250 ms task still risk the next interaction, and when do you usescheduler.yield(),setTimeout,requestIdleCallback,isInputPending(deprecated in favour of yielding), and Web Workers? - P7: the Long Animation Frames (LoAF) API reported a 55 ms frame with
scripts: [{ src: 'third-party.js', invoker: '#document.onclick', dur: 54 }]. How does LoAF improve on the Long Tasks API for attribution, and how would you use it in RUM?
T4. CLS
- P2 measured CLS on a 390 px phone: an image without dimensions 0.308, with
width/height0.000; a web font swap 0.133; a banner inserted above content 0.108, with reserved space 0.000; a toast animated withtop0.010, withtransform0.000. Explain each, and how CLS is scored (impact × distance fractions, session windows, shifts within 500 ms of input excluded). - P2's font experiments: fallback metric overrides measured from the actual fonts (
size-adjust: 126.5%plus ascent/descent/line-gap overrides) gave 0.000; guessed values (118%, 85%) gave 0.018; and a fallback@font-faceusinglocal('Arial')on a machine without Arial gave 0.195, worse than no adjustment. What does that teach about font fallback tuning, and what do tools likenext/fontand Fontaine automate? - List the other common CLS sources (ads and embeds, cookie banners pushing content, skeletons with the wrong size, infinite scroll inserting above, late-loading fonts in icon fonts, client-side A/B tests) and the fix for each.
T5. JavaScript cost: bundles, splitting, tree shaking, lazy loading, prefetching
- Why is a byte of JavaScript more expensive than a byte of image (download, then parse, compile and execute on the main thread; the lab's eager 664 KB build delayed page-ready to 1,369 ms vs 183 ms when split)?
- P4 bundled
debouncefive ways:import _ from 'lodash'→ 73,785 B (26 KB gzip);import { debounce } from 'lodash'→ 73,781 B (the same: no tree shaking);lodash-es→ 2,902 B;lodash/debounce→ 3,461 B. And for dates: moment 63,948 B, date-fnsformat19,877 B,Intl.DateTimeFormat94 B. Explain why named imports fromlodashdon't shake, what tree shaking requires (ES modules, static imports,sideEffects: false), and how to keep dependencies in check. - The lab's code-splitting trade-off: lazy loading made the page ready 7× sooner but the first click on Reports took 1,737 ms; prefetching on idle gave 189 ms and 464 ms. Where should TiffinBox split (routes, heavy widgets like maps and charts, rarely used dialogs, admin tools), and what prefetch strategies do routers use (on hover, on viewport, on idle, speculation rules: chapter 18's gaps)?
T6. Images, fonts and CDN caching
- Write the checklist for TiffinBox's dish images: format (AVIF/WebP with fallbacks), responsive
srcset/sizes, dimensions,loading="lazy"except for LCP images,fetchpriority,decoding="async", compression quality, and an image CDN. Use chapter 24's P6 numbers (AVIF 10.7 KB vs JPEG 20.8 KB at 640 px). - Fonts:
font-displayvalues (swap, optional, fallback), preloading only critical fonts, subsetting per script (Latin, Devanagari, Telugu), variable fonts, self-hosting vs Google Fonts, and fallback metrics (T4). What's the minimum font setup for a fast kitchen page? - CDN caching for performance (chapter 19): what to cache at the edge (static assets immutably, HTML with short
s-maxage+ stale-while-revalidate, images), how CDN hit ratio affects TTFB, and why a CDN can't fix slow uncached HTML for logged-in pages.
T7. Virtualisation and memory leaks
- P5 rendered 10,000 menu rows: 363 ms and 40,006 elements fully rendered, versus 2 ms and 95 elements virtualised; adding one stylesheet rule affecting every row took 241 ms with the full list and 1 ms virtualised. Explain what virtualisation does, what it costs (scroll handling, variable heights, accessibility of off-screen items, find-in-page, SEO), and when
content-visibility: autois a simpler alternative. - The lab's leak: each visit to the orders page added 10,000 DOM nodes and a listener (200,048 nodes after 20 visits). List the common SPA leak patterns (listeners on window/document, timers and intervals, subscriptions, detached DOM kept by closures, caches without limits, third-party widgets not destroyed) and how to find them (heap snapshots, "detached elements", allocation timelines,
performance.memory/measureUserAgentSpecificMemory). - How do you write a leak test that runs in CI (navigate in and out N times, force GC, compare DOM node and listener counts or heap size)?
T8. Worker offloading
- What can move to a Web Worker (parsing, filtering, sorting, search indexing, image processing, cryptography, diffing, compression) and what can't (DOM access, most of React rendering)? What do OffscreenCanvas, worklets and libraries like Comlink add?
- P6: filtering and sorting 300,000 objects took 116 ms on the main thread (longest main-thread gap 117 ms); in a worker the total was 277 ms (187 ms of compute in the worker) and the main thread was still blocked for 90 ms, by copying the data with
postMessage. Sending a 40 MBFloat64Arraytook 80 ms by copy (46 ms main-thread gap) and 41 ms by transfer (25 ms gap). Explain structured clone, transferables andSharedArrayBuffer, and how to design worker offloading that actually helps. - For TiffinBox's partner portal, a CSV import of 50,000 order rows freezes the page. Design the fix with a worker, progress reporting, cancellation and memory considerations.
T9. Performance tools
- Map tools to questions: Lighthouse (audit), DevTools Performance panel (what happened on the main thread), the Network panel (waterfall: chapter 19's T9), WebPageTest (filmstrips, real devices and locations, multi-step), the
web-vitalslibrary and CrUX (field), the React/Angular profilers (component renders), bundle analyzers, Performance Insights / Lighthouse's LCP sub-parts. - Walk through reading a Performance panel trace of a slow tap: the interaction track, the main thread flame chart (long task, event handler, style recalculation, layout, paint), and how to attribute to your code vs third parties.
- Which RUM fields should TiffinBox collect (metric values, rating, attribution: LCP element and sub-parts, INP interaction target and phases and LoAF scripts, CLS largest shift source; page type, device memory, effective connection type, logged in), and how do you avoid RUM hurting performance or privacy?
Programming exercises
P1. Diagnose and fix an LCP problem
Take a page whose hero is a CSS background image (or JS-inserted), 2 MB, lazy-loaded by mistake. Measure LCP and its four sub-parts with web-vitals/attribution in Playwright (or DevTools' LCP breakdown) on a throttled profile. Fix discovery (an <img> in the HTML, preload), priority (fetchpriority="high", remove loading="lazy"), bytes (responsive AVIF/WebP), and render delay (render-blocking CSS/JS). Record each sub-part after each fix.
P2. Hunt down layout shifts
Build eight variants of a kitchen page on a 390 px viewport and measure CLS with a layout-shift observer: an image with and without dimensions; a web font swap without and with fallback metric overrides (measured, guessed, and with a local() font that doesn't exist); a banner inserted at the top with and without reserved space; a toast animated with top vs transform. Then compute correct fallback metrics for your brand font.
P3. Split and prefetch a heavy widget
The order tracking page includes a 300 KB map library, used only after the order is out for delivery. Split it with dynamic import() (or React.lazy/@defer), prefetch it on idle once the order is "preparing", and show a sized placeholder. Measure initial JS, time to interactive and time from "out for delivery" to the map appearing, for eager, lazy and prefetched versions.
P4. Measure tree shaking and dependency weight
Bundle a one-line use of debounce via lodash default import, lodash named import, lodash-es and lodash/debounce; and a date format via moment, date-fns and Intl.DateTimeFormat. Record minified and gzip sizes. Then run a bundle analyzer on your app, list the five largest dependencies per route, and replace or lazy-load two of them. Add no-restricted-imports rules.
P5. Virtualise the menu and measure
Render a 10,000-dish list fully and virtualised (by hand or with TanStack Virtual). Measure initial render time, DOM element count, the cost of a global style change, memory, and INP for typing in a filter. Add content-visibility: auto as a third variant. Check accessibility (row count announced, keyboard scrolling, find-in-page).
P6. When a worker helps, and when it doesn't
Filter and sort 300,000 objects on the main thread and in a worker, measuring total time and the longest main-thread gap with a heartbeat timer. Then send a 40 MB typed array by copy and by transfer. Redesign the worker version so the main-thread gap is under 10 ms for each search.
P7. Attribute slow interactions with LoAF and web-vitals
Add a third-party script that does 50 ms of work on every document click, and your own click handler with a 150 ms sort. Observe long-animation-frame entries and the web-vitals/attribution INP report, and identify which script caused what. Then fix your handler (update first, yield, or move to a worker) and contain the third party (load it later, or replace it).
P8. A leak test in CI
Reproduce the lab's leaky orders page (each visit leaves a table and a listener behind), fix it, and write a Playwright test that navigates in and out 20 times, forces garbage collection via CDP, and asserts DOM nodes, listeners and heap stay bounded. Make the leaky version fail and the fixed version pass.
P9. Set up RUM for Core Web Vitals
Add web-vitals/attribution to the app, send metrics with attribution and context via sendBeacon (sampled), store them, and build a p75 dashboard per page template and device class. Compare a week of field data with your lab numbers, and find the worst page and its main cause.
Cumulative projects (chapters so far: Volume 1, and Volume 2's 00, 12–27)
C1. A performance budget and plan for the kitchen page
Set budgets for the kitchen page on a mid-range Android profile over 4G (LCP ≤ 2.0 s p75 field, INP ≤ 150 ms, CLS ≤ 0.05, JS ≤ 120 KB gzip, images ≤ 300 KB above the fold), measure the current state in lab and field, and implement the plan: server rendering and CDN caching (chapters 19, 24), LCP image fixes (P1), font metrics (P2), route-level and widget-level splitting with prefetching (P3), dependency diet (P4), content-visibility for long menus (P5), yielding in handlers (P7), and RUM (P9). Gate budgets in CI and report results after two weeks of field data.
Combines: HTTP and CDN caching (ch 19), browser rendering (ch 18), full-stack rendering strategies (ch 24), React performance (ch 22), testing budgets (ch 26) and this chapter.
C2. Make the partner portal fast on kitchen tablets
Kitchen staff use old Android tablets (2 GB RAM) running the partner portal all day. Profile a lunch-rush session (an order board with 200 orders and SSE updates every few seconds), and fix: change detection or re-render costs (chapter 23's OnPush and signals, chapter 22's memoisation), DOM size (virtualise or content-visibility), timers (one shared clock), memory leaks over 8 hours (P8), worker offloading for CSV exports (T8), and INP for tapping "Accept". Measure CPU, memory over time, and INP before and after.
Combines: Angular change detection and signals (ch 23), state management and caching (ch 25), real-time updates (ch 19), UI architecture (ch 21's C3) and this chapter.
C3. Investigate a field regression after a release
After release 4.12, RUM shows kitchen page INP p75 on mobile went from 160 ms to 320 ms, LCP unchanged, and conversion dipped 4%. Lab tests didn't flag it. Investigate with RUM attribution (interaction targets, phases, LoAF scripts), release diffs, bundle analysis and Performance panel recordings on a real mid-range device; find the cause and fix; and add a check that would have caught it.
Combines: testing and CI (ch 26), React rendering (ch 22), state management selectors (ch 25), UI architecture (ch 21) and this chapter's tools.
What the chapter leaves out
Network-level performance and resource hints
Beyond caching: HTTP/3 and connection reuse (chapter 19's S3), preconnect and dns-prefetch for critical third-party origins, 103 Early Hints, priority hints on fetch() (priority: 'low' for analytics), compression (Brotli, zstd, compression dictionaries: chapter 19's T5), avoiding redirects (each costs a round trip), and fewer origins. On mobile networks in India, round trips matter more than bandwidth, so cutting requests on the critical path often beats shaving bytes.
Third-party script governance
Analytics, tag managers, chat widgets, A/B testing, ads and social embeds often dominate main-thread time (P7). Governance: an inventory with owners and business value, a performance budget per third party, loading strategies (after consent, on interaction, on idle, with async/defer), facades (a static "chat" button that loads the widget on click), self-hosting where licences allow, Partytown (moving some third-party scripts to a worker), and RUM attribution by script source to hold vendors accountable.
Performance in single-page navigations
Core Web Vitals were designed around full page loads; SPA route changes ("soft navigations") aren't measured as new LCPs by default (Chromium has a soft-navigation measurement experiment). Measure route transitions yourself (time from click to the new view's main content rendered, using performance.mark and the Event Timing API), keep INP low during transitions (transitions and yielding: chapter 22's T7), and prefetch route data and code (T5).
Rendering performance details
Some performance work happens below JavaScript: avoiding forced synchronous layouts (reading layout after writes in loops: chapter 18), keeping style recalculation cheap (simple selectors, fewer elements affected by class changes), using will-change and compositor-only animations sparingly (layer memory on low-end GPUs), contain for isolating layout, and avoiding large box-shadow/filter effects on scrolling elements. The Performance panel's Rendering tab (paint flashing, layer borders, FPS meter) shows these costs.
Energy and data efficiency
Performance also means using less energy and data: fewer bytes (prepaid plans), less CPU (battery, heat), fewer wake-ups (polling vs push: chapter 19's T8), respecting Save-Data and prefers-reduced-data (experimental), and pausing work in background tabs (visibilitychange). Sustainable web design practices (smaller pages, efficient caching) align with performance goals and reduce emissions per page view.
Senior exercises
S1. Make the business case for a performance programme
Leadership asks whether to spend a quarter on performance. Write the one-page case: current field data vs competitors (CrUX), the link between speed and TiffinBox's conversion (from your own A/B test or RUM correlation, not only industry studies), the plan, the cost, risks, and how success will be measured.
S2. Review a performance-sensitive pull request
A PR adds a "top dishes this week" carousel to the kitchen page: it imports a full carousel library (90 KB) and moment, fetches data in a useEffect after hydration, renders 30 full-resolution images (loading="eager"), auto-advances every 3 s with setInterval (never cleared), animates slides with left, and inserts itself above the menu when data arrives. Write the review.
S3. Decide between performance techniques under a deadline
Two weeks before a marketing campaign, the kitchen page's mobile LCP p75 is 3.6 s and INP is 260 ms. You can do three of: migrate the page to Server Components (large), add an image CDN, remove the chat widget from kitchen pages, split and prefetch the reviews and map code, compute font fallback metrics, virtualise the menu, add yielding to filter handlers, enable CDN caching for kitchen HTML. Choose with expected impact, effort and risk, using RUM attribution to justify.
S4. Design a performance-aware component library
The design system (chapter 21) should make fast UIs the default. Specify performance rules for its components: images (an <Image> with required dimensions and sizes), icons (inline SVG sprites, not icon fonts, per-icon imports), carousels and tabs (no auto-advance, lazy panels), lists (virtualisation built in above N items), modals (lazy content, no layout shift), animations (transform/opacity only, reduced motion), bundle size budgets per component, and how you'll measure and enforce them.
S5. Teach performance with one page and three metrics
Prepare a 20-minute session using the lab and this chapter's outputs to teach LCP, INP and CLS: one before/after per metric, the one cause to remember for each, and five rules.