18. The Optimization Playbook
“Premature optimization is the root of all evil. Measured optimization is the root of all good reviews.”— with apologies to Donald Knuth
The story: the slow kitchen
Section titled “The story: the slow kitchen”A restaurant hires a consultant because service is slow. The consultant doesn’t start by buying faster stoves. She stands in the corner for an evening with a stopwatch and a notebook. She finds: the waiters walk to the far end of the kitchen for every plate because the pass is badly placed; the chef re-reads the whole recipe book for every order; the dishwasher is blocking the doorway; and the cooks wait for one oversized delivery of vegetables every morning that arrives at 11:55.
None of these fixes needs a new stove. All of them need measurement first, then the obvious thing in the right order.
That’s this chapter. Chapters 5–17 gave you the mechanisms and the measurements. Here’s the playbook: for each kind of resource, the few fixes that matter most. Then we’ll take a deliberately slow app and fix it in order, measuring after each step, so you see which fixes move which numbers.
The prime directive: measure, fix the biggest thing, measure again. Don’t do all twenty things at once; you won’t know which helped, and some “optimizations” make things worse.
Images
Section titled “Images”Images are usually the largest bytes on a page and frequently the LCP element.
- Right format. AVIF typically gives the smallest files for photos at good quality, WebP is a close and widely supported second; JPEG remains the universal fallback. Serve the best format each browser supports with
<picture>(multiple<source type>) or content negotiation at an image CDN. PNG for photos is almost always a mistake; SVG for icons and illustrations. - Right size. Never send a 4000-pixel-wide image to a 400-pixel slot. Use responsive images:
<img src="monsoon-800.avif" srcset="monsoon-400.avif 400w, monsoon-800.avif 800w, monsoon-1600.avif 1600w" sizes="(max-width: 700px) 100vw, 700px" width="1600" height="900" alt="Rain over Marine Drive at dusk" fetchpriority="high">srcset lists candidates with their widths; sizes tells the browser how wide the image will be displayed at each viewport, before layout; the browser picks the best candidate for the device’s pixel density. Getting sizes wrong (or omitting it — the default is 100vw) is the most common reason phones download desktop-sized images.
3. Dimensions always. width and height attributes (or CSS aspect-ratio) reserve space, so the image doesn’t shift layout when it loads: CLS 0 for images, for free.
4. Loading strategy. Hero/LCP image: in the HTML, not lazy, fetchpriority="high" (Chapter 9). Everything below the fold: loading="lazy" and decoding="async".
5. Image CDNs. Services (Cloudinary, imgix, Cloudflare Images, framework image optimizers) resize, re-encode and cache on the fly from one master image: …/monsoon.jpg?w=800&f=auto&q=70. They make the right thing the easy thing.
6. Decode cost. Big images cost memory and decode time on phones. A 1600-wide AVIF is fine; a 6000-wide one shown at 400 px wastes megabytes of RAM.
Recall the author’s audit: two videos, 7.7 MB, 97% of the repo, uncompressible by gzip. Video playbook:
- Encode for the web: an appropriate resolution (decorative loops rarely need more than 720p), a reasonable bitrate, no audio track if muted, short loops. Offer a modern codec (AV1 or VP9 in WebM, or HEVC where supported) and H.264 MP4 as a fallback via multiple
<source>elements; the browser takes the first it can play. - Don’t load it until needed:
preload="none"(ormetadata), a poster image (small, correctly sized — it’s often the LCP element), and load/play the video when it scrolls into view (IntersectionObserver). - Respect context: no autoplay with
prefers-reduced-motionor Save-Data;muted playsinlineif autoplaying a decorative loop (browsers block autoplay with sound). - Adaptive streaming for anything longer than a short loop: HLS or DASH split the video into segments at multiple bitrates; the player adapts to the network. Use a video platform or a streaming service rather than serving a single 50 MB MP4.
- Consider not using video: an animated image sequence, a CSS animation, or a still image with a subtle effect can carry the same mood for a fraction of the bytes.
Web fonts block or shift text (Chapter 10’s FOIT/FOUT). Playbook:
- Fewer fonts, fewer weights. Each weight and style is a file. Variable fonts can replace several files with one (but check the total size).
- WOFF2 only, self-hosted on your origin (avoids a new connection; Chapter 5), with long-lived caching.
- Subset: strip glyphs you don’t use. A Latin-only subset of a font is often a fraction of the full file. For Hindi, Tamil, Bengali and other scripts, use
unicode-rangeso the browser downloads a script’s file only if the page uses those characters. font-display:swapshows fallback text immediately and swaps when loaded (good for body text, at the cost of a reflow);optionaluses the web font only if it’s available almost immediately (e.g., cached), otherwise sticks with the fallback for that page view — no layout shift, best for performance.- Preload the one critical font (
<link rel="preload" as="font" type="font/woff2" crossorigin>), not all of them. - Metric-matched fallbacks: define a fallback
@font-facewithsize-adjust,ascent-override,descent-overrideandline-gap-overrideso the system fallback occupies the same space as the web font. The swap then changes the glyphs but not the layout: no CLS. Frameworks (e.g., Next.js’s font module) can generate these automatically. - Or: use system fonts. This book does. Zero requests, zero shift, native rendering.
JavaScript
Section titled “JavaScript”The most expensive bytes (Chapter 11). Playbook in order of typical impact:
- Measure what you ship. A bundle analyzer (treemap of your bundles) and the Coverage tab (how much of each file actually executes on load). Most apps find a library they didn’t know was there.
- Remove dependencies. The best code is no code. Big date libraries → native
Intland small utilities; lodash → native methods; modal/tooltip libraries →<dialog>/popover (Chapter 14); a charting library on the homepage → load it only on the chart’s route. - Split by route and by interaction (Chapter 1): route chunks, and dynamic
import()for heavy features behind a click (editor, map, video player). - Ship less to the client architecturally: server components, islands, static generation (Chapter 7). Every component that doesn’t hydrate is JS you don’t send.
- Break up long tasks and yield (Chapter 11). Reduce hydration cost.
- Modern output: don’t transpile and polyfill for browsers you don’t support (Chapter 1).
- Compression: Brotli for static JS (Chapter 6).
Third-party script governance
Section titled “Third-party script governance”Third-party scripts — analytics, tag managers, A/B testing, chat widgets, ads, social embeds — are frequently the single largest source of main-thread work and long tasks on commercial sites, and they’re added by people who never see a performance trace.
- Inventory every third-party script, its owner, its purpose and its cost (Performance panel “Third parties” summary, or block each domain in DevTools and measure the difference).
- Budget them: total third-party JS, number of origins, main-thread time.
- Load later:
async/defer, after the page is interactive, or on interaction (“load the chat widget when the user clicks the chat button” — a facade: a lightweight lookalike that loads the real thing on demand). - Offload: tools in the style of Partytown run some third-party scripts in a web worker, proxying their DOM access — effective for some scripts, fragile for others; test carefully.
- Server-side alternatives: send analytics events from your server; proxy tag managers server-side.
- Review quarterly. Remove what nobody uses.
- Small and same-origin first — CSS is render-blocking (Chapter 9).
- Remove unused CSS: Coverage shows it; utility-first frameworks that generate only used classes help; old global stylesheets accumulate dead rules for years.
- Critical CSS for heavy pages: inline the above-the-fold styles, load the rest non-blocking. Worth it when the full CSS is large; often unnecessary when it’s small.
- Avoid
@importchains (waterfalls). - Containment and
content-visibilityfor long pages (Chapter 10). - Cheap effects: be deliberate with large blurs,
backdrop-filter, big shadows and many layers (Chapter 10).
Caching and delivery
Section titled “Caching and delivery”Chapter 6’s strategy, applied:
- Hashed assets
immutablefor a year; HTML revalidated (and edge-cached briefly withstale-while-revalidateif possible). - A CDN in front of everything, with HTTP/2 and HTTP/3, Brotli, TLS 1.3.
- Fewer origins on the critical path; preconnect to the essential one or two that remain.
- bfcache-eligible pages (no
unloadhandlers) and Speculation Rules prerendering for likely next pages (Chapter 9). - A service worker for repeat visits where it makes sense (Chapter 12).
The server and the edge
Section titled “The server and the edge”TTFB is the foundation every loading metric sits on.
- Static wherever possible (SSG/ISR) — the fastest server is no server.
- Edge caching of HTML, even for a few seconds, with
stale-while-revalidate. - Streaming SSR so the shell isn’t held hostage by the slowest query (Chapter 7).
- Fix slow data: database indexes, N+1 query patterns, caching expensive computations, moving data closer to compute.
- 103 Early Hints to start fetching critical CSS/fonts while the server is still thinking.
- Avoid redirect chains (each one is a round trip).
Case study: fixing a slow app, step by step
Section titled “Case study: fixing a slow app, step by step”Here’s an illustrative case, modelled on a typical content-plus-interactivity app: “Lumen-Slow”, a photo-essay site built the way many sites get built — client-rendered React SPA, a big UI library, a date library with all locales, Google-hosted fonts, a 2.4 MB hero JPEG set as a CSS background, a chat widget and two analytics tags in the head, no image dimensions.
All numbers below are lab measurements on a simulated mid-range Android on a Slow-4G-like profile, median of five runs. They’re illustrative of the direction and rough size of each fix’s effect, which is the lesson; your app’s numbers will differ.
Baseline: LCP 6.8 s, TBT 1,450 ms, CLS 0.31, JS 820 KB compressed, total 4.1 MB.
Step 1 — Fix the hero. The LCP breakdown showed a resource load delay of ~3 s: the hero was a CSS background, discovered only after CSS loaded and the JS app rendered the container. Change: a real <img> in the HTML shell with srcset/sizes, AVIF with JPEG fallback, width/height, fetchpriority="high". File size 2.4 MB → ~160 KB at the phone’s display size. LCP 6.8 → 4.9 s; CLS 0.31 → 0.12 (dimensions reserved). Still slow: the HTML is still an empty CSR shell, so the image can’t render until JS runs.
Step 2 — Render on the server. Essays don’t change per user: move them to static generation (Chapter 7). The HTML now contains the essay and the hero; FCP and LCP no longer wait for JS. LCP 4.9 → 3.1 s; TBT 1,450 → 980 ms (hydration still heavy); CLS → 0.05 (content no longer pops in).
Step 3 — Put JavaScript on a diet. Bundle analysis: the UI library imported wholesale (~180 KB), the date library with every locale (~70 KB), a charting library on every page (~110 KB) used only on /stats. Changes: per-component imports, Intl.DateTimeFormat instead of the date library, the chart split into the /stats route chunk, essay body as server components with only the like button and lightbox as client components. JS 820 → 210 KB; TBT 980 → 610 → 290 ms (two sub-steps), LCP → 2.6 s (less render-blocking main-thread work).
Step 4 — Govern third parties. The chat widget (~150 ms of main thread at load) moves behind a facade button; the two analytics tags become one, loaded async after load. TBT 290 → 180 ms; LCP → 2.3 s.
Step 5 — Fonts. Google-hosted fonts → self-hosted, subset WOFF2, preload the one body font, font-display: swap with metric-matched fallback. One fewer origin on the critical path; no swap shift. LCP → 2.1 s; CLS → 0.01.
Step 6 — Caching and delivery. Hashed assets immutable, HTML edge-cached with stale-while-revalidate, HTTP/3 at the CDN, unload handler removed for bfcache, Speculation Rules for essay links. First-visit LCP → 1.8 s; repeat visits and back/forward navigations become near-instant (not shown in a cold-load number — check field data).
Result (lab): LCP 6.8 → 1.8 s, TBT 1,450 → 160 ms, CLS 0.31 → 0.01, JS 820 → 210 KB. In the field, you’d expect mobile p75 to move from “poor” on all three vitals to “good” — and you’d verify that in RUM and CrUX over the following weeks rather than assume it.
Notice the order: the first two steps were architectural (where the hero is discovered; where HTML is made) and moved LCP the most. The JS diet moved TBT (and so INP) the most. Fonts and caching were polish. That ordering is typical.
Budgets in the pipeline
Section titled “Budgets in the pipeline”Chapter 3’s pipeline gets teeth:
- Size budgets with a tool like
size-limit: declare a maximum compressed size per entry point; CI fails if a PR exceeds it, and comments the diff on the PR. Deterministic and cheap — the best early-warning system.
[ { "path": ".next/static/chunks/main-*.js", "limit": "90 KB" }, { "path": ".next/static/chunks/pages/index-*.js", "limit": "40 KB" }]- Lighthouse CI with assertions: run Lighthouse a few times against key URLs of the built app; assert on metrics and audits, with tolerance for noise.
{ "ci": { "assert": { "assertions": { "largest-contentful-paint": ["error", { "maxNumericValue": 2500 }], "total-blocking-time": ["error", { "maxNumericValue": 200 }], "cumulative-layout-shift": ["error", { "maxNumericValue": 0.1 }], "unused-javascript": ["warn", {}]} } } }- Field budgets monitored in RUM (Chapter 23 alerts when p75 crosses a threshold after a release).
Budgets are only useful if someone owns them. Make the budget part of the PR template (“budget impact: +3 KB on /”), and treat a budget increase as a decision with a reason, not a silent edit to a config file.
What you now know
Section titled “What you now know”You have a playbook for images (format, srcset/sizes, dimensions, priority, CDNs), video (encoding, posters, preload, lazy, adaptive streaming), fonts (subsetting, font-display, preloading, metric-matched fallbacks), JavaScript (analysis, removal, splitting, server-rendering, yielding, third-party governance), CSS, caching and the server; you’ve seen the order in which fixes typically pay off; and you can enforce budgets in CI with size checks and Lighthouse assertions — with an owner.
Self-quiz
Section titled “Self-quiz”1. What does sizes tell the browser, and what’s the default?
The displayed width of the image at each viewport, before layout; default 100vw (often causing oversized downloads).
2. Why doesn’t gzip help video, and what does?
Video is already compressed; better encoding, smaller resolution, lazy loading with posters, and adaptive streaming help.
3. How do metric-matched fallback fonts prevent CLS?
size-adjust and ascent/descent overrides make the fallback occupy the same space as the web font, so the swap doesn’t move text.
4. Which step in the case study moved LCP most, and why?
Server-rendering (and fixing hero discovery): the content and hero were in HTML immediately instead of waiting for JS.
5. Why are size budgets better early warnings than Lighthouse scores?
They’re deterministic and cheap per PR; Lighthouse is noisy lab data.
Exercises
Section titled “Exercises”Warm-up 1. Fix the markup. <img src="hero-4000.jpg" loading="lazy"> above the fold. List every fix.
Solution
srcset/sizes with modern formats, width/height, remove lazy, add fetchpriority=“high”, alt text.
Warm-up 2. Which drawer? LCP sub-parts: TTFB 0.3 s, load delay 0.1 s, load duration 2.2 s, render delay 0.2 s. Which fixes?
Solution
Load duration: compress/resize the image (AVIF, srcset), image CDN, HTTP/3. Discovery is already fine.
Warm-up 3. Third-party math. A chat widget adds 160 ms of main-thread time at load; 3% of visitors use chat. What do you propose?
Solution
A facade: show a lightweight button; load the real widget on click. 97% of visitors pay nothing.
Lab 4. Lumen-Slow. Deliberately slow down a copy of Lumen (CSS background hero, CSR, big libraries, a third-party widget in head, no dimensions). Record a baseline (5 runs, median). Then apply the case study’s steps one at a time, recording metrics after each.
Expected outcome
A before/after table like Figure 18.2 for your own app, and a clear sense of which fix moves which metric.
Lab 5. Fonts without shift. Add a web font to Lumen with a metric-matched fallback; record CLS with and without the overrides.
Expected outcome
With overrides, the swap shows no layout-shift region in the Rendering tab.
Lab 6. Budgets in CI. Add size-limit and Lighthouse CI assertions to Lumen’s pipeline. Open a PR that adds a 60 KB dependency and watch it fail.
Hint
Run Lighthouse CI against the production build served locally in CI; use multiple runs to reduce noise.
Lab 7. Video done right. If you have a background video (or the author’s), re-encode it at an appropriate size in two codecs, add a poster, preload="none", lazy play on visibility, and no autoplay under reduced motion. Compare transferred bytes for a visitor who never scrolls to it.
Expected outcome
Near-zero video bytes for visitors who don’t reach it; a much smaller file for those who do.
Staff 8. The optimization roadmap. For a real product, write a one-page roadmap: top three problems from field data, fixes in order with expected impact and effort, and how you’ll verify.
Model outline
Field evidence (p75 by route/device), diagnosis (sub-parts/phases), fixes ranked by impact ÷ effort, verification plan (lab per PR, field over 28 days), risks.
Staff 9. Budget governance. Write the rules for how your team changes a performance budget.
Model answer
Budgets live in the repo; increases need a PR with reason, owner and expiry; reviewed by a perf owner; field impact reviewed after release; quarterly re-baselining.