FE·27
Frontend Performance
Measuring and improving what users feel: Core Web Vitals (LCP, INP, CLS) and FCP/TTFB, long tasks, JavaScript cost, code splitting, tree shaking, lazy loading and prefetching, images and fonts, virtualisation, memory leaks, workers, CDN caching, and the tools to diagnose each.
Start here: making pages fast
Why speed is a feature
Users notice delay quickly and leave: large studies by Google and others keep finding that bounce rates and abandoned purchases climb steeply as load time grows from one second to several. Speed matters most for exactly the users many products serve worst: people on mid-range Android phones, patchy mobile networks and expensive data plans. And performance is measured by search engines: Google uses page experience signals, including Core Web Vitals, in ranking.
"Fast" means three different things to a user, and each has a metric:
| The user asks… | Metric | Good | Poor |
|---|---|---|---|
| "Is it loading? Can I see the main content?" | LCP (Largest Contentful Paint): when the biggest image or text block appears | ≤ 2.5 s | > 4 s |
| "Does it respond when I tap?" | INP (Interaction to Next Paint): how long the slowest typical interaction takes to show a response | ≤ 200 ms | > 500 ms |
| "Does it stay still, or jump around?" | CLS (Cumulative Layout Shift): how much visible content moves unexpectedly | ≤ 0.1 | > 0.25 |
These three are Google's Core Web Vitals, judged at the 75th percentile of real users' visits (so most users must have a good experience, not just the average). Supporting metrics help find causes: TTFB (time to first byte, server and network) and FCP (First Contentful Paint, when anything appears).
Lab data and field data
- Lab data comes from a controlled test: Lighthouse, the DevTools Performance panel, WebPageTest, or scripts like the ones in this volume. It's repeatable, so it's good for debugging and for catching regressions in CI.
- Field data (real-user monitoring, RUM) comes from your actual visitors, collected with the
web-vitalslibrary or seen in Chrome's public CrUX dataset and PageSpeed Insights. It's what users really experience, on devices and networks you'd never test.
Use field data to know whether you have a problem and lab data to find why.
A slow page, fixed step by step
Here's a home page as it's often first built: a full-size 3000 × 2000 photo exported as PNG (11.8 MB), a stylesheet and an analytics script from slow third-party servers in the <head>, no image dimensions, and a promotional banner inserted by JavaScript after a second:
<head>
<link rel="stylesheet" href="/slow-theme.css"> <!-- takes 800 ms -->
<script src="/slow-analytics.js"></script> <!-- takes 600 ms, blocks parsing -->
</head>
<body><header>Sharma's Tiffin</header><main><div id="banner"></div>
<img class="hero" src="/hero-original.png" alt="Breakfast spread">
…
The fixed version changes no content, only how it's delivered:
<head>
<style>/* the few rules needed for the first screen, inlined */</style>
<link rel="preload" as="image" href="/hero-800.webp" imagesrcset="/hero-800.webp 800w, /hero-1200.webp 1200w"
imagesizes="(max-width: 60rem) 100vw, 60rem" fetchpriority="high">
<link rel="stylesheet" href="/slow-theme.css" media="print" onload="this.media='all'"> <!-- loads without blocking -->
<script src="/slow-analytics.js" defer></script>
</head>
<body><header>Sharma's Tiffin</header><main><div id="banner" style="min-height:3.5rem"></div>
<img class="hero" src="/hero-800.webp" srcset="/hero-800.webp 800w, /hero-1200.webp 1200w"
sizes="(max-width: 60rem) 100vw, 60rem" width="1200" height="800" fetchpriority="high" alt="Breakfast spread">
Measured (median of three loads each):
/before FCP 952 ms | LCP 10904 ms | CLS 0.042 | bytes 11543 KB | hero file hero-original.png
/after FCP 144 ms | LCP 172 ms | CLS 0.000 | bytes 89 KB | hero file hero-1200.webp
From 10.9 seconds to under 0.2 to see the main content, and from 11.5 MB to 89 KB of data, with no change to what the user sees. Each change attacks one cause:
- Right-size and re-encode images. The phone screen is 412 CSS pixels wide (about 1,070 device pixels at its 2.6× density), so a 3,000-pixel PNG wastes almost everything.
srcsetandsizeslet the browser pick the smallest file that's sharp enough (it chose the 1,200-pixel version); WebP or AVIF cut bytes by 5–10× over PNG or JPEG for photos. This one change is often the biggest win on real sites. - Don't block rendering on things the first screen doesn't need. Inline the small amount of CSS the first screen needs, load the rest without blocking, and
deferscripts (chapter 12's lab measured why). - Tell the browser what matters most.
fetchpriority="high"and apreloadstart the hero image immediately at high priority. - Reserve space for anything that arrives later:
widthandheighton images, amin-heighton the banner slot. CLS went to zero.
The levers, in one list
Almost every performance fix is one of these:
- Send less: smaller images, less JavaScript (code splitting, removing unused libraries, tree shaking), compression (chapter 19).
- Send it sooner: caching and CDNs, preloading critical resources, server rendering for content (chapter 24), HTTP/2 and 3.
- Do less on the main thread: split long tasks, defer non-urgent work, move heavy computation to workers, avoid layout thrashing (chapter 17), render only what's visible.
- Don't move things around: reserve space, avoid inserting content above what the user is reading, animate with
transform.
Responsiveness: INP
LCP is about loading; INP is about every tap and keypress for the whole visit. An interaction's time is the sum of three parts: input delay (the main thread was busy when the user tapped), processing (your event handlers running) and presentation (style, layout and paint of the new frame). The browser's Event Timing API reports all three. An "Add to cart" button whose click handler also does 250 ms of other work (recalculating offers, analytics, saving), three ways:
all work in the handler interaction 256 ms (input delay 3, processing 250, presentation 3)
update UI first, defer the rest interaction <16 ms
split with scheduler.yield() interaction <16 ms
The work is the same; what changed is when the user gets visual feedback. Update what the user is waiting for first, then defer or slice the rest (chapter 15's lab measured the same idea for input delay).
How deep to go in frontend performance
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 | Name the Core Web Vitals, their thresholds, and the main levers |
| L2 | Optimise images, fonts, CSS and script loading; split code; avoid layout shifts |
| L3 | Explain the critical rendering path, resource priorities, the main-thread budget, INP's three phases, caching and bundling trade-offs |
| L4 | Diagnose LCP, INP and CLS problems from traces and field data; find long tasks, leaks and oversized bundles |
| L5 | Set performance budgets and architecture (rendering strategy, data loading, third-party policy) for a product |
| L6 | Run performance as a practice: RUM dashboards, regression gates in CI, budgets per team, device-tiered experiences |
Metrics
Why performance matters and how it's measured
Performance is user experience. Slower pages convert worse, bounce more, and rank lower, since Core Web Vitals are a Google search ranking signal. On low-end Android phones (the median device in many markets, India included), the same JavaScript can take 4–10× longer to execute than on a developer's MacBook. Always test on realistic devices and networks.
There are two kinds of data:
| Lab (synthetic) | Field (RUM: real user monitoring) | |
|---|---|---|
| Source | Lighthouse, WebPageTest, DevTools on a controlled device and network | web-vitals library / PerformanceObserver in real users' browsers; Chrome UX Report (CrUX) |
| Good for | Debugging, CI regression checks, reproducibility | The truth: real devices, networks, caches, user behaviour |
| Limits | One configuration; can't measure real interactions well (INP) | Noisy; needs traffic; harder to debug |
Google's thresholds are evaluated at the 75th percentile of page loads in the field. "Good" means 75% of your users' visits meet the threshold, not the average visit.
Core Web Vitals
| Metric | Measures | Good | Needs improvement | Poor |
|---|---|---|---|---|
| LCP: Largest Contentful Paint | Loading: when the largest image or text block in the viewport rendered | ≤ 2.5 s | ≤ 4.0 s | > 4.0 s |
| INP: Interaction to Next Paint | Responsiveness: latency from a tap, click or keypress to the next frame, across the whole visit (roughly the worst interaction) | ≤ 200 ms | ≤ 500 ms | > 500 ms |
| CLS: Cumulative Layout Shift | Visual stability: how much visible content unexpectedly moves | ≤ 0.1 | ≤ 0.25 | > 0.25 |
Supporting metrics:
| Metric | Meaning | Good |
|---|---|---|
| TTFB: Time to First Byte | Request start → first byte of the HTML (redirects + DNS + TCP + TLS + server time) | ≤ 0.8 s |
| FCP: First Contentful Paint | First text or image painted | ≤ 1.8 s |
| TBT: Total Blocking Time (lab) | Sum of the parts of long tasks over 50 ms between FCP and interactivity: a lab proxy for INP | ≤ 200 ms |
| Speed Index (lab) | How quickly the viewport visually fills in |
LCP
LCP is usually the hero image, a heading or text block, or a poster frame. Break it down into four sub-parts and fix the biggest:
- TTFB: a slow server, no CDN, redirect chains, cold serverless starts, slow data fetching before streaming. Fixes: CDN caching of HTML (SSG/ISR), streaming SSR, edge, fewer redirects,
103 Early Hints. - Resource load delay: the LCP image is discovered late (a CSS background, injected by JavaScript, client-rendered), is
loading="lazy"(never lazy-load the LCP image), or has low priority. Fixes: put it in the HTML as an<img>, addfetchpriority="high", and<link rel="preload">it if it must come from CSS. - Resource load duration: the image is too big. Fixes: responsive
srcset/sizes, AVIF or WebP, compression, a CDN image service, appropriate dimensions. - Element render delay: the image arrived, but rendering is blocked by CSS or JS, waiting for a client-side framework to render it (CSR), or waiting on a web font (for text LCP). Fixes: SSR/SSG, inline critical CSS, defer non-critical JS,
font-display: swap.
SPAs that render everything client-side typically have poor LCP, because the LCP element can't paint until JS downloads, runs and fetches data. That's a waterfall built into the architecture (chapter 24).
INP
INP (Interaction to Next Paint) replaced FID in March 2024. For each click, tap or keypress, it measures the time from the input until the next frame is painted, and reports roughly the worst interaction of the visit (the 98th percentile for pages with many interactions). Each interaction has three phases:
input delay → the main thread was busy with something else (a long task) when the user clicked
processing duration → your event handlers (and the framework re-render they trigger)
presentation delay → style/layout/paint/composite of the resulting frame (huge DOM, layout thrashing)
Fixes, by phase:
- Input delay: break up long tasks (chapter 15: yield with
scheduler.yield()), defer third-party scripts, reduce hydration work (islands, RSC,@defer), and avoid heavy timers and intervals. - Processing: do the minimum before the next paint. Update the UI first (show a pressed or pending state), then do heavy work after yielding or in a transition (
startTransition, chapter 22) or a worker. Debounce expensive handlers. Avoid synchronous layout reads in handlers. - Presentation: keep the DOM small (under about 1,500 nodes is a good target), virtualise long lists, use
content-visibility: autofor off-screen sections, avoid layout thrashing (chapter 18), and keep style recalculation cheap.
button.addEventListener("click", async () => {
button.setAttribute("aria-busy", "true"); // 1. immediate visual feedback (cheap)
await scheduler.yield?.(); // 2. let the browser paint that frame
const result = expensiveRecalculation(); // 3. heavy work after the paint
render(result);
});
Diagnose INP with field data (the web-vitals attribution build reports the slow element, event type and phase breakdown), the Long Animation Frames API (which script caused it), and DevTools Performance recordings of real interactions.
CLS
CLS sums unexpected layout shifts: elements moving without user input. The score of each shift is impact fraction × distance fraction, and shifts are grouped into windows (bursts within 1 s, max 5 s), with the worst window reported. Shifts within 500 ms of a user input don't count. Common causes and fixes:
| Cause | Fix |
|---|---|
| Images, videos or iframes without dimensions | width/height attributes or aspect-ratio (chapter 13) |
| Ads, embeds or banners injected above content | Reserve space (min-height); insert below the viewport; use overlays that don't push content |
| Web fonts swapping and reflowing text | font-display: optional or size-adjusted fallbacks (size-adjust, ascent-override; next/font does this), and preloading fonts |
| Late-loading content (cookie banners, "you have 3 new messages") | Reserve space, or render it as an overlay |
Animations of top, height or margin |
Animate transform instead (chapter 18) |
| Client-rendered content replacing server skeletons of different size | Skeletons with the real dimensions |
Back-forward cache restores, and SPA route changes that preserve layout, also help, because instant navigations don't shift.
FCP and TTFB
TTFB is the foundation: nothing can paint before the first byte. It's dominated by network distance (use a CDN or edge, and HTTP/3), redirects (http → https → www, each costing a round trip), server rendering time, and data waterfalls on the server. Measure server timing with the Server-Timing response header (Server-Timing: db;dur=53, render;dur=12), which shows up in DevTools and RUM. FCP follows TTFB plus render-blocking resources: make CSS small and critical-first, use no parser-blocking scripts, and preconnect to critical origins. Streaming SSR improves both, because the shell flushes immediately.
JavaScript cost
Long tasks
Any task over 50 ms on the main thread is a long task (chapter 15). It blocks input (hurting INP), delays rendering, and stalls animations that aren't on the compositor. Common sources: hydration of large component trees, parsing and evaluating large bundles at startup, third-party scripts (tag managers, chat widgets, A/B testing, ad tech), big JSON parses, sorting or filtering large arrays in render, synchronous localStorage on large data, and framework re-renders cascading across the app.
Find them in the DevTools Performance panel (red triangles on tasks), with Long Animation Frames attribution in the field, and with Lighthouse's TBT and "Avoid long main-thread tasks". Fix them by doing less (ship less JS, render less), doing it later (defer, lazy-load, requestIdleCallback), breaking it up (yield every ~40 ms), or doing it elsewhere (Web Workers, the server).
JS bundle size
JavaScript is the most expensive resource byte for byte. A 300 KB JPEG and a 300 KB script cost similar download time, but the image only needs decoding (often off the main thread), while the script must be parsed, compiled and executed on the main thread. On a low-end phone, 1 MB of JS can mean seconds of main-thread work. The HTTP Archive median page ships about 500+ KB of compressed JavaScript on mobile, which is far more than most pages need.
Measure what you ship:
$ npx vite-bundle-visualizer # treemap of what's in each chunk (or rollup-plugin-visualizer)
$ ANALYZE=true next build # @next/bundle-analyzer
$ ng build --stats-json && npx esbuild-visualizer --metadata dist/stats.json
$ npx source-map-explorer dist/assets/*.js
Common bloat: entire utility libraries (lodash, moment with every locale; use lodash-es with per-function imports, or native methods, and date-fns/Temporal/Intl instead of moment), duplicate copies of a dependency at different versions, polyfills for browsers you don't support, icon packs imported whole, client-side markdown or syntax highlighting that could happen on the server, and large charting or editor libraries loaded on pages that don't use them. Track size with budgets in CI (chapter 26): size-limit, Angular budgets, Lighthouse CI.
Code splitting
Code splitting breaks the bundle into chunks loaded on demand, so users download the code for what they're doing now:
- Route-based splitting: each route is its own chunk. Frameworks do this automatically (Next.js, React Router framework mode, Angular
loadComponent/loadChildren, SvelteKit, Nuxt). - Component-based splitting: heavy, rarely used components (a rich-text editor, charts, a map, a PDF viewer, a date-range picker) load only when needed:
React.lazy(() => import("./Chart"))with<Suspense>, Angular@defer, ornext/dynamic. - Interaction-based: load on intent (hover over the "Export" button, then import the export module).
- Vendor chunking: put stable third-party code in separate long-cached chunks. Bundlers do this heuristically. Avoid creating hundreds of tiny chunks, because each request has overhead.
The trade-off is that over-splitting creates request waterfalls: chunk A loads, which then discovers it needs chunk B. Mitigate with modulepreload hints (frameworks emit them for route chunks), and by prefetching likely next chunks.
Tree shaking
Tree shaking removes exports that are never imported. It's dead-code elimination (Vol. 1 ch. 10) at the module level, made possible because ES modules have static import/export declarations the bundler can analyse:
// utils.js
export function used() { … }
export function unused() { … } // removed from the bundle if nothing imports it
// app.js
import { used } from "./utils.js"; // ✓ static, analysable
// const utils = require("./utils"); // ✗ CommonJS: dynamic, much harder to shake
// import * as utils from "./utils"; // usually fine if you only use utils.used statically
What defeats it:
- CommonJS dependencies (
require,module.exports): prefer packages that ship ESM. - Side effects at module top level (registering globals, polyfills, CSS imports): the bundler must keep a module that might have side effects. Packages declare
"sideEffects": false(or a list) inpackage.jsonto promise they can be dropped safely. - Barrel files (
index.tsre-exporting everything) in some setups, which pull in and evaluate more than needed, especially in dev servers and tests. Prefer direct imports for large libraries, or rely on bundler optimisations (optimizePackageImportsin Next.js). - Classes with many methods (methods can't be shaken individually) and dynamic property access.
Lazy loading
Lazy loading defers non-critical resources until they're needed:
- Images and iframes:
loading="lazy"(native, chapter 13). Never on the LCP image. - Components and routes: dynamic
import()(code splitting, above). - Below-the-fold sections:
@defer (on viewport)in Angular,IntersectionObserver+lazy()in React, Astro'sclient:visible. - Third-party widgets (chat, video embeds, maps): a facade, meaning a lightweight static placeholder (a screenshot plus a play button) that loads the real widget on click. A YouTube embed costs about 500 KB+ of JS before anyone presses play, while a facade costs about 5 KB.
- Heavy rendering of off-screen content: CSS
content-visibility: autowithcontain-intrinsic-sizelets the browser skip layout and paint for off-screen sections, which can cut rendering time dramatically on long pages.
Prefetching
Prefetching loads resources for the likely next step during idle time, so navigation feels instant:
- Framework link prefetching: Next.js
<Link>prefetches routes in the viewport, React Router<Link prefetch="intent">prefetches on hover or focus, and Angular has preloading strategies. - Speculation Rules (chapter 13): prefetch or prerender whole pages on hover (Chromium) for multi-page apps, which makes them near-instant.
<link rel="prefetch">for specific likely resources.- Data prefetching:
queryClient.prefetchQueryon hover (chapter 25).
Be considerate: respect navigator.connection.saveData and slow connections, don't prefetch on metered connections aggressively, and measure the hit rate, since prefetches that aren't used waste users' data and your server capacity.
Assets
Image optimisation
Images are usually the largest bytes on a page, and often the LCP element:
| Technique | Detail |
|---|---|
| Right format | AVIF (best compression, slower to encode) > WebP > JPEG for photos. SVG for icons and logos. PNG only when you need lossless output with sharp edges. Serve through <picture> or content negotiation |
| Right size | Never send a 4000 px image to a 400 px slot. Use srcset + sizes (chapter 13) or an image CDN that resizes on the fly (?w=800&fmt=auto) |
| Right priority | LCP image: fetchpriority="high", not lazy, preloaded if discovered late. Everything else below the fold: loading="lazy", decoding="async" |
| Reserve space | width/height or aspect-ratio → no CLS |
| Compression | Tune quality (AVIF q≈50–60, WebP q≈75–80 often look identical to the original) |
| Placeholders | A dominant-colour background, tiny blurred LQIP, or BlurHash for perceived speed |
| Caching | Content-hashed URLs + immutable, served from a CDN |
Font optimisation
Web fonts can delay text rendering (FOIT, a flash of invisible text) or cause layout shifts (FOUT/CLS when the font swaps in):
font-display:swap(show fallback text immediately, then swap: good for body text, but can shift layout),optional(use the web font only if it loads very quickly, otherwise keep the fallback for that visit: best for CLS), andblock(avoid).- Self-host WOFF2 files (one less third-party connection, and the HTTP cache is partitioned per site anyway, so a shared Google Fonts cache no longer helps).
next/fontand Fontsource automate this. - Subset to the characters and languages you need (
unicode-range), and use variable fonts (one file for all weights) instead of six static files. - Preload the one or two critical font files (
<link rel="preload" as="font" type="font/woff2" crossorigin>). - Match fallback metrics with
size-adjust,ascent-override,descent-overrideandline-gap-overrideon a fallback@font-face, so the swap barely moves text. - Consider a system font stack for UI text (
system-ui, -apple-system, "Segoe UI", Roboto, sans-serif), which costs zero bytes.
CDN caching
A CDN (content delivery network: Cloudflare, Akamai, Fastly, CloudFront, Vercel, Netlify) caches content at hundreds of points of presence near users. That cuts latency (shorter round trips, which also speeds up the TCP/TLS handshake and slow-start ramp-up, Vol. 1 ch. 9) and offloads your origin.
- Static assets: content-hashed names +
Cache-Control: public, max-age=31536000, immutable(chapter 19). They're served from the edge forever. - HTML: cache at the CDN with short TTLs plus
stale-while-revalidate, or SSG/ISR pages, while browsers revalidate (s-maxage=60, stale-while-revalidate=600withmax-age=0). - API responses: cache public, read-heavy endpoints at the edge (catalogues, configuration), with cache keys chosen carefully (
Vary, query normalisation) and surrogate keys (tags) for targeted purges. - Never cache personalised responses in shared caches. Watch out for
Set-Cookieon cached responses, and forAuthorizationhandling. Misconfigured CDN caching has leaked user data between customers in real incidents.
Also use HTTP/3, Brotli or Zstandard compression, 103 Early Hints, and image optimisation at the edge. Chapter 31 covers cache invalidation strategies for deploys.
Runtime
Virtualisation
Rendering 10,000 rows creates 10,000+ DOM nodes. That means a slow initial render, slow style and layout on every change (chapter 18), heavy memory, and terrible INP. Virtualisation (windowing) renders only the rows visible in the viewport plus a small overscan, and positions them inside a container sized to the full list height:
import { useVirtualizer } from "@tanstack/react-virtual";
function OrderList({ orders }: { orders: Order[] }) {
const parentRef = useRef<HTMLDivElement>(null);
const v = useVirtualizer({ count: orders.length, getScrollElement: () => parentRef.current, estimateSize: () => 48, overscan: 8 });
return (
<div ref={parentRef} style={{ height: 600, overflow: "auto" }}>
<div style={{ height: v.getTotalSize(), position: "relative" }} role="list" aria-rowcount={orders.length}>
{v.getVirtualItems().map(item => (
<div key={item.key} role="listitem" aria-posinset={item.index + 1} aria-setsize={orders.length}
style={{ position: "absolute", top: 0, left: 0, width: "100%", transform: `translateY(${item.start}px)` }}>
<OrderRow order={orders[item.index]} />
</div>
))}
</div>
</div>
);
}
Libraries: TanStack Virtual (React, Vue, Solid, Svelte, Angular), react-window and react-virtuoso, Angular CDK cdk-virtual-scroll-viewport, and data-grid libraries (AG Grid). Caveats: find-in-page can't see unrendered rows, screen readers need aria-setsize and aria-posinset (chapter 20), variable row heights need measurement, and keeping scroll position across navigation needs care. For moderately long lists (hundreds of rows), content-visibility: auto may be enough, with no JavaScript.
Memory leaks
A frontend memory leak is memory that stays reachable after it's no longer needed, so the garbage collector (Vol. 1 ch. 10) can't free it. In long-lived SPAs (dashboards left open all day), leaks show up as growing memory, slower GCs, jank, and eventually tab crashes ("Aw, Snap!" out-of-memory). Usual culprits:
| Leak | Fix |
|---|---|
Event listeners on window/document added by components and never removed |
Remove them in cleanup (useEffect return, ngOnDestroy, DestroyRef), or use an AbortSignal to remove many at once (chapter 17) |
setInterval/setTimeout still running after unmount |
clearInterval in cleanup |
| RxJS subscriptions never unsubscribed | async pipe, takeUntilDestroyed, toSignal |
| Detached DOM trees: removed elements still referenced from JS (caches, closures, arrays) | Drop the references, use WeakMap/WeakRef for element caches (chapter 15) |
| Ever-growing caches (Map keyed by query, logs, undo stacks) | Bound them (LRU, Vol. 1 ch. 3), configure query gcTime |
| Closures capturing large objects (a handler that closes over a whole dataset) | Capture only what's needed |
| Third-party widgets not destroyed on route change (maps, charts, editors) | Call their destroy()/dispose() in cleanup |
| WebSockets, observers (Intersection, Resize, Mutation) left connected | close() / disconnect() in cleanup |
Finding them with Chrome DevTools' Memory panel: take a heap snapshot, perform the action (open and close a dialog ten times), force GC, take another snapshot, and compare. Look for growing counts of your components' objects, and "Detached" DOM nodes (filter "Detached"). The Retainers view shows the reference chain keeping each one alive. The Performance panel's memory track shows the sawtooth (healthy) versus staircase (leaking) pattern. performance.measureUserAgentSpecificMemory() (cross-origin isolated pages) measures memory in the field.
Worker offloading
Move CPU-heavy, DOM-free work off the main thread to Web Workers (chapter 17), keeping the UI responsive:
- Parsing and transforming large datasets (CSV, JSON, Excel), filtering and sorting big tables.
- Search indexing and fuzzy matching (FlexSearch, MiniSearch).
- Image processing, compression and encryption, diffing, syntax highlighting, markdown rendering.
- WebAssembly computation (chapter 29).
- Running third-party scripts in a worker (Partytown proxies DOM calls from analytics tags).
// With Comlink: a worker that feels like an async module
// worker.ts
import { expose } from "comlink";
const api = { filterAndSort(rows: Row[], q: string) { return rows.filter(r => r.name.includes(q)).sort(byDate); } };
expose(api);
// main.ts
import { wrap } from "comlink";
const worker = wrap<typeof import("./worker").api>(new Worker(new URL("./worker.ts", import.meta.url), { type: "module" }));
const result = await worker.filterAndSort(rows, query); // runs on another thread
Costs: messages are copied (structured clone, chapter 15), so sending 50 MB back and forth can cost more than the work saved. Transfer ArrayBuffers instead, or keep the data in the worker and send only queries and results. Workers also have startup cost, so reuse them.
Performance tools
| Tool | Use |
|---|---|
| Chrome DevTools Performance panel | Record loads and interactions; flame charts of main-thread tasks; long tasks; layout and paint; Web Vitals annotations; CPU and network throttling; the live metrics view shows LCP, INP and CLS as you interact |
| DevTools Network panel | Waterfall, priorities, protocol (h2/h3), caching, initiators (who requested what), blocking |
| DevTools Coverage panel | Unused JS and CSS bytes per file: candidates for splitting or removal |
| DevTools Memory panel | Heap snapshots, allocation timelines, detached nodes |
| Lighthouse (DevTools, CLI, CI) | Lab audit with scores and specific suggestions |
| PageSpeed Insights | Lighthouse plus field CrUX data for your URL or origin |
| WebPageTest | Real devices and locations, filmstrips, waterfalls, multi-step scripts, comparisons |
| CrUX / Search Console | Google's field data from real Chrome users |
RUM (web-vitals + your analytics, or Sentry, Datadog RUM, SpeedCurve, Vercel Speed Insights) |
Your users' real metrics with attribution: which page, element, device and interaction |
| React DevTools Profiler / Angular DevTools | Component render counts and timings, "why did this render?" |
| Bundle analysers | What's in your JS (above) |
A performance workflow that works: (1) set budgets and SLOs from field data (p75 LCP ≤ 2.5 s, INP ≤ 200 ms); (2) find the worst pages and metrics in RUM; (3) reproduce them in the lab with matching throttling (a mid-range Android device on "Slow 4G" with 4× CPU slowdown); (4) fix the biggest contributor; (5) guard against regressions in CI; (6) verify in field data after deploy. Measure before you optimise. Vol. 1's "measure, don't guess" applies here too.
Lab: performance, measured
All experiments ran in Chromium 153 through Playwright, emulating a mid-range phone with the DevTools protocol: CPU slowed 4× (Emulation.setCPUThrottlingRate), downloads limited to 10 Mbit/s (Network.emulateNetworkConditions), and a 412 × 915 viewport at 2.6× pixel density. Web Vitals were read with PerformanceObserver exactly as the web-vitals library does.
Experiment 1: the slow page, change by change
The Start here section showed the before and after. Here's how the page's main resource, the hero image, behaved in each version, from the Network panel's point of view:
file bytes discovered by priority
before hero-original.png 11.8 MB main parser, after default (Low until laid out)
slow CSS and script
after hero-1200.webp 88 KB preload in <head> High (fetchpriority)
LCP: 10,904 ms → 172 ms total transfer: 11,543 KB → 89 KB CLS: 0.042 → 0.000
The single biggest factor was bytes: at 10 Mbit/s an 11.8 MB image takes about 9.5 seconds to download however early it starts. But the order matters too, and it's easy to get wrong after fixing the file size: in the "before" version the parser didn't reach the <img> until the 600 ms analytics script had run, and Chromium initially fetches images at low priority until layout shows they're in the viewport. Preload plus fetchpriority="high" removes both delays. On real sites the same audit usually finds the LCP element is a CSS background or a JavaScript-rendered image the preload scanner can't see (chapter 18's lab), or a lazy-loaded hero.
Experiment 2: INP's three phases
An "Add to cart" handler that also does 250 ms of unrelated work, measured with the Event Timing API (PerformanceObserver with type: "event", which is how INP is computed):
// all work in the handler
spin(250); count.textContent = ++n;
// update UI first, defer the rest
count.textContent = ++n; setTimeout(() => spin(250), 0);
// split with scheduler.yield()
count.textContent = ++n; for (let i = 0; i < 25; i++) { await scheduler.yield(); spin(10); }
all work in the handler interaction 256 ms (input delay 3, processing 250, presentation 3)
update UI first, defer the rest interaction <16 ms (below the 16 ms reporting threshold)
split with scheduler.yield() interaction <16 ms
INP only counts the time until the next paint after the interaction, so moving non-visual work after that paint fixes it. The two fixes differ in what happens next: a single deferred 250 ms task will still block the next interaction if the user taps again quickly (showing up as input delay), while yielding every 10 ms keeps the page responsive throughout. When the work is pure computation (parsing a big file, filtering 100,000 rows), a Web Worker (chapter 29) takes it off the main thread entirely.
Experiment 3: code splitting, and its cost
A page that uses a large library (axe-core, 663 KB minified) only on a "Reports" screen, built with esbuild three ways:
import axe from "axe-core"; // eager: in the main bundle
const { default: axe } = await import("axe-core"); // lazy: a separate chunk, loaded on click
requestIdleCallback(() => import("axe-core")); // lazy + prefetch when the page is idle
eager build: eager.js 663.8 KB
lazy build: lazy.js 0.3 KB + axe-ZTDMEQ6M.js 663.2 KB (loaded on demand)
eager page ready after 1369 ms | Reports result after clicking: 437 ms
lazy page ready after 183 ms | Reports result after clicking: 1737 ms
prefetch page ready after 189 ms | Reports result after clicking: 464 ms
Splitting made the page ready 7× sooner, because the browser no longer downloaded, parsed and compiled 663 KB of JavaScript before the app could start. But plain lazy loading moved that cost to the moment the user clicks Reports: 1.7 seconds of waiting. Prefetching the chunk when the browser is idle gets both benefits: a fast start and a fast click. Routers and frameworks do this for routes (prefetch on link hover or visibility); the principle is to load code for what the user is doing now, and fetch what they'll probably do next in the background.
Experiment 4: a memory leak in a single-page app
An orders page renders a 2,000-row table and adds a resize listener on window whose closure references the table. The user "navigates" to it 20 times without a reload (as in any SPA). After each batch of visits, the test forced garbage collection and read Chromium's counters (Runtime.getHeapUsage, Memory.getDOMCounters):
const onResize = () => { table.dataset.w = innerWidth; }; // the closure keeps the table alive
window.addEventListener("resize", onResize); // leaky: never removed
// fixed:
const ac = new AbortController();
window.addEventListener("resize", onResize, { signal: ac.signal });
cleanup = () => ac.abort(); // called before rendering the next page
leaky (tables actually in the page: 1)
5 visits: 0.7 MB, 50018 DOM nodes, 5 listeners
10 visits: 1.2 MB, 100028 DOM nodes, 10 listeners
15 visits: 1.6 MB, 150038 DOM nodes, 15 listeners
20 visits: 2.1 MB, 200048 DOM nodes, 20 listeners
fixed (tables actually in the page: 1)
5 visits: 0.7 MB, 10010 DOM nodes, 1 listeners
20 visits: 0.8 MB, 10010 DOM nodes, 1 listeners
Only one table was ever on screen, but the leaky version kept every old one alive: 10,000 detached DOM nodes per visit, growing without limit, because each forgotten listener's closure still referenced its table. On a phone, long sessions end with a sluggish tab or a crash. The fix is the cleanup discipline frameworks build in (React effect cleanups, Angular's DestroyRef, AbortController signals). To find leaks: take two heap snapshots in DevTools' Memory panel around a repeated action and look for growing "Detached" DOM trees, or watch the DOM node counter in the Performance monitor.
Try it yourself
- Run Lighthouse (DevTools → Lighthouse, mobile) on a site you work on. For its LCP element, find out how it was discovered, at what priority it was fetched, and how many bytes it was.
- Add the
web-vitalslibrary to a page and logonLCP,onINPandonCLSwith theirattributionbuilds. Which element and which interaction does each blame? - In experiment 3, prefetch on hover over the Reports button instead of on idle. How much of the delay does a typical 300 ms hover hide?
- Recreate experiment 4 in React: a component that adds a window listener in an effect without returning a cleanup. Watch the counters while navigating between routes.
Revision sheet: frontend performance
Key ideas
- Core Web Vitals at p75 of real users: LCP (loading), INP (responsiveness), CLS (visual stability); supporting TTFB, FCP, TBT (lab proxy for INP).
- LCP = TTFB + resource load delay + resource load time + element render delay; fix the largest phase: server and caching, discoverability and priority (preload,
fetchpriority, no lazy hero), bytes (responsive modern images), render-blocking resources. - INP = input delay + processing + presentation; yield (
scheduler.yield()), update UI first, debounce, move work to workers, keep the DOM small, avoid layout thrashing. - CLS: reserve space (dimensions,
aspect-ratio, min-heights), no content inserted above,font-displaywith metric overrides, animate transforms. - JavaScript cost: download + parse + compile + execute; budgets; code splitting by route and interaction; tree shaking (ES modules,
sideEffects); prefetching likely next code; audit dependencies. - Assets: AVIF/WebP,
srcset/sizes, CDN image resizing; fonts (WOFF2, subsetting, preload,font-display: swap/optional); HTTP caching with hashed files. - Runtime: virtualise long lists,
content-visibility, avoid leaks (cleanups, AbortController), memory profiling. - Tools: Lighthouse, DevTools Performance (with throttling), WebPageTest, CrUX/PageSpeed Insights, RUM with
web-vitals, Lighthouse CI budgets.
Numbers to remember
- LCP ≤ 2.5 s good, > 4 s poor; INP ≤ 200 ms good, > 500 ms poor; CLS ≤ 0.1 good, > 0.25 poor.
- Long task > 50 ms; frame 16.7 ms.
- Lab: an 11.8 MB hero PNG → 88 KB WebP took LCP from 10.9 s to 0.17 s; splitting a 663 KB library made the page ready 7× sooner.
Pitfalls
- Optimising lab scores while field data stays poor (or the reverse); testing only on fast laptops.
- Lazy-loading the LCP image; hero images in CSS backgrounds; carousels as the first screen.
- Third-party scripts (tags, chat widgets, A/B testing) loaded synchronously.
- Lazy-loading code without prefetching, moving the delay to the user's first click.
- Huge client bundles hidden by fast networks in development.
- Listeners, intervals and subscriptions without cleanup in SPAs.
Glossary
- Critical rendering path: the resources and steps needed before the first render.
- Render-blocking resource: CSS or synchronous script that delays rendering.
- Field data / RUM: measurements from real user sessions.
- Performance budget: an agreed limit (bytes, LCP, INP) enforced in CI.
- Tree shaking: removing unused exports at build time.
- Detached DOM: nodes removed from the document but still referenced from JavaScript.