Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 30 min · revision 3

Lab: Profile, Fix and Budget a Slow Storefront

Take a deliberately slow storefront through one full loop: measure LCP, CLS and INP under fixed throttling with a field-style beacon, fix the hero image, the layout shift and the blocking handlers, re-measure, and enforce the result with a budget check that fails a CI job.

Contentsand lesson path

What you will learn

  • Measure Core Web Vitals (LCP, INP, CLS) in the lab and in the field, state the 75th-percentile thresholds for a good experience, and attribute a poor score to its cause.
  • Optimize loading with responsive modern-format images, font loading strategy, resource hints and fetch priority, HTTP caching and code splitting by route and interaction.
  • Improve responsiveness by breaking up long tasks, deferring non-critical work and removing unnecessary React re-renders, verified with the Performance panel and React Profiler.
  • Set and enforce performance budgets (initial JavaScript size, LCP, CLS) with bundle analysis and automated Lighthouse checks.

Prerequisites: How Browsers Render Pages

01. Goal and setup

You will take a broken storefront through one full performance loop: record a baseline, profile the slow click down to the function responsible, fix the three problems the numbers name, re-measure, and wire a budget that fails when the numbers creep back. Every output below was captured by running exactly the files printed here. Timings depend on the machine, so compare before and after on the same machine, never your numbers against the ones printed here.

You need: Node 22.2 or later (this lab ran on Node v22.23.2, which has zlib.crc32), npm, and a terminal. The measuring browser is the Chromium that Playwright 1.64.1 downloads (Chrome for Testing 156.0.8078.4 here). No Lighthouse install is needed for the core loop; a Lighthouse cross-check is one of the stretch goals at the end.

Create the project, install Playwright and its browser:

Terminal · project skeleton
mkdir -p perf-lab/www/storefront perf-lab/www/storefront-fixed perf-lab/www/shared
cd perf-lab && npm init -y && npm pkg set type=module
npm install --no-audit --no-fund -D [email protected]
npx playwright install chromium
Project layout when you have created every file below
perf-lab/
├── make-images.mjs        writes www/hero.png and www/hero-800.png
├── server.mjs             static files, a slow-stylesheet switch, a beacon sink
├── measure.mjs            throttled lab run that reads the beacons back
├── profile.mjs            CPU profile of one click: which function ran
├── budget-check.mjs       the CI gate
└── www/
    ├── rum.js             field beacon: LCP, CLS and INP with sub-parts
    ├── shared/block.js    a side-effect-free busy-wait helper
    ├── storefront/        the slow page: index.html, store.css, app.js
    └── storefront-fixed/  your fixed copy: index.html, app.js

The hero must be a real, decodable image: a browser only treats an image as an LCP candidate once it can paint it, and it can only reserve or move a box whose size it knows. This script writes two genuine PNG files with Node built-ins — a 2000 × 1400 original and an 800 × 560 version — using a fixed seed, so you get the same bytes printed here.

JavaScript · make-images.mjs
// Writes two real PNG photos-in-miniature with Node built-ins only.
import { writeFileSync } from "node:fs";
import { crc32, deflateSync } from "node:zlib";

function chunk(type, data) {
  const out = Buffer.alloc(12 + data.length);
  out.writeUInt32BE(data.length, 0);
  out.write(type, 4, "latin1");
  data.copy(out, 8);
  out.writeUInt32BE(crc32(out.subarray(4, 8 + data.length)), 8 + data.length);
  return out;
}

function png(width, height, seed) {
  let s = seed; // small deterministic PRNG, so every learner gets the same bytes
  const rand = () => ((s = (s * 1103515245 + 12345) >>> 0) >>> 16) / 65536;
  const raw = Buffer.alloc((width * 3 + 1) * height);
  for (let y = 0; y < height; y++) {
    const row = y * (width * 3 + 1); // byte 0 of each row: filter type 0
    const t = y / height;
    for (let x = 0; x < width; x++) {
      const grain = rand() < 0.05 ? 16 : 0; // sparse film grain
      const water = t > 0.6 ? 40 * Math.sin(x / 9 + y / 3) : 0; // ripples
      raw[row + 1 + x * 3] = 230 - 150 * t + grain;
      raw[row + 2 + x * 3] = 120 - 40 * t + grain + water / 2;
      raw[row + 3 + x * 3] = 90 + 80 * t + grain + water;
    }
  }
  const header = Buffer.alloc(13);
  header.writeUInt32BE(width, 0);
  header.writeUInt32BE(height, 4);
  header[8] = 8; // bit depth
  header[9] = 2; // colour type: RGB
  return Buffer.concat([
    Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
    chunk("IHDR", header),
    chunk("IDAT", deflateSync(raw, { level: 9 })),
    chunk("IEND", Buffer.alloc(0)),
  ]);
}

for (const [name, w, h] of [["hero.png", 2000, 1400], ["hero-800.png", 800, 560]]) {
  const file = png(w, h, 42);
  writeFileSync(`www/${name}`, file);
  console.log(`www/${name} ${w}x${h} ${Math.round(file.length / 1024)} KB`);
}
Terminal
node make-images.mjs
Expected output
www/hero.png 2000x1400 466 KB
www/hero-800.png 800x560 137 KB

The server serves www/, delays any file requested with ?delay=ms, holds every PNG back for 300 ms to imitate a far-away image host, and keeps the beacons it receives so the measuring script can read them back. It listens on 127.0.0.1 only.

JavaScript · server.mjs
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { extname, join, normalize } from "node:path";

const types = { ".html": "text/html; charset=utf-8", ".css": "text/css",
  ".js": "text/javascript", ".png": "image/png" };
const rum = [];

createServer(async (req, res) => {
  const url = new URL(req.url, "http://x");
  if (req.method === "POST" && url.pathname === "/collect") {
    let raw = "";
    req.on("data", (c) => (raw += c));
    req.on("end", () => {
      console.log("BEACON", raw);
      rum.push(JSON.parse(raw));
      res.writeHead(204).end();
    });
    return;
  }
  if (url.pathname === "/collected.json") {
    res.writeHead(200, { "content-type": "application/json" });
    return res.end(JSON.stringify(rum));
  }
  try {
    // ?delay=ms slows any file; images always wait 300 ms, like a far-away CDN
    const delay = Number(url.searchParams.get("delay") || 0)
      + (extname(url.pathname) === ".png" ? 300 : 0);
    if (delay) await new Promise((r) => setTimeout(r, delay));
    const rel = url.pathname.endsWith("/")
      ? url.pathname.slice(1) + "index.html"
      : url.pathname.slice(1);
    const body = await readFile(join("www", normalize(rel)));
    res.writeHead(200, { "content-type":
      types[extname(rel)] || "application/octet-stream",
      "cache-control": "no-store" });
    res.end(body);
  } catch {
    res.writeHead(404).end("not found");
  }
}).listen(8901, "127.0.0.1", () => console.log("perf-lab on :8901"));

Now the slow storefront. It has three deliberate faults: a render-blocking stylesheet that takes 700 ms, a full-size hero marked loading="lazy" with no width or height, and click handlers that block the main thread. Both scripts are ES modules (type="module"), because app.js uses import; a classic <script> would stop at that line with a syntax error and attach no handlers at all.

HTML · www/storefront/index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Estuary Store</title>
  <link rel="stylesheet" href="store.css?delay=700">
</head>
<body>
  <h1>Estuary Fine Goods</h1>
  <img src="../hero.png" loading="lazy" alt="Estuary at dusk">
  <p>Hand-thrown mugs, linen and oak boards from the estuary workshops.
    Free delivery on orders over £50.</p>
  <ul>
    <li>Stoneware mug — £18</li>
    <li>Linen tea towel — £12</li>
    <li>Oak serving board — £45</li>
    <li>Rope doorstop — £22</li>
    <li>Beeswax candle — £9</li>
  </ul>
  <div class="actions">
    <button id="add">Add to cart</button>
    <button id="dispatch">Prepare dispatch</button>
    <span id="badge">0</span>
    <p id="status"></p>
  </div>
  <script type="module" src="app.js"></script>
  <script type="module" src="../rum.js"></script>
</body>
</html>
CSS · www/storefront/store.css
body { font-family: sans-serif; margin: 2rem; max-width: 800px; }
h1 { font-size: 1.8rem; margin-bottom: 1rem; }
img { display: block; max-width: 100%; height: auto; margin-bottom: 1rem; }
.actions { display: flex; flex-wrap: wrap; align-items: center; gap: 1rem; }
button { padding: 0.5rem 1rem; font-size: 1rem; cursor: pointer; }
#badge { font-weight: bold; background: #e2e8f0; padding: 0.2rem 0.6rem; }
JavaScript · www/shared/block.js
// Side-effect free: importing this module only defines a function.
export function blockFor(ms) {
  const end = performance.now() + ms;
  while (performance.now() < end) { /* busy wait: stands in for real work */ }
}
JavaScript · www/storefront/app.js
import { blockFor } from "../shared/block.js";

const add = document.getElementById("add");
const dispatch = document.getElementById("dispatch");
const badge = document.getElementById("badge");
const status = document.getElementById("status");
let count = 0;

add.addEventListener("click", () => {
  blockFor(300);                // shipping rates
  count += 1;
  badge.textContent = String(count);
  status.textContent = "Added to cart";
  blockFor(120);                // analytics and storage
});

dispatch.addEventListener("click", () => {
  blockFor(240);
  status.textContent = "Dispatched";
});

Last, the field beacon. The field-data lesson uses the web-vitals library, and that is what production code should use. This lab uses a dependency-free version so that nothing needs bundling and you can read every line: it observes the same browser entries — largest-contentful-paint, layout-shift and event — splits LCP into its four sub-parts and INP into its three, and sends one JSON beacon when the page is hidden. Treat it as a teaching tool.

JavaScript · www/rum.js
// A dependency-free field beacon for this lab. In production use the web-vitals
// library: it also handles back/forward-cache restores, prerendering and the
// INP rule that skips one outlier per 50 interactions.
const ttfb = performance.getEntriesByType("navigation")[0].responseStart;
let lcp = null, cls = 0, win = 0, first = 0, last = 0;
const interactions = new Map();                 // interactionId -> timings

new PerformanceObserver((list) => {
  lcp = list.getEntries().at(-1);
}).observe({ type: "largest-contentful-paint", buffered: true });

new PerformanceObserver((list) => {
  for (const e of list.getEntries()) {
    if (e.hadRecentInput) continue;          // shifts right after input are expected
    const sameWindow = e.startTime - last < 1000 && e.startTime - first < 5000;
    win = sameWindow ? win + e.value : e.value;
    if (!sameWindow) first = e.startTime;
    last = e.startTime;
    cls = Math.max(cls, win);                // CLS = the worst session window
  }
}).observe({ type: "layout-shift", buffered: true });

function onEvents(list) {
  for (const e of list.getEntries()) {         // pointerdown, pointerup, click...
    if (!e.interactionId) continue;
    const i = interactions.get(e.interactionId) ?? { start: e.startTime,
      procStart: e.processingStart, procEnd: 0, end: 0 };
    i.start = Math.min(i.start, e.startTime);
    i.procStart = Math.min(i.procStart, e.processingStart);
    i.procEnd = Math.max(i.procEnd, e.processingEnd);
    i.end = Math.max(i.end, e.startTime + e.duration); // the next paint
    interactions.set(e.interactionId, i);
  }
}
// "event" skips entries under 16 ms; "first-input" always reports the first one.
new PerformanceObserver(onEvents)
  .observe({ type: "event", durationThreshold: 16, buffered: true });
new PerformanceObserver(onEvents).observe({ type: "first-input", buffered: true });

function worstInteraction() {
  let worst = null;
  for (const i of interactions.values()) {
    if (!worst || i.end - i.start > worst.end - worst.start) worst = i;
  }
  return worst && { inp: Math.round(worst.end - worst.start), inpParts: {
    inputDelay: Math.round(worst.procStart - worst.start),
    processing: Math.round(worst.procEnd - worst.procStart),
    presentation: Math.round(worst.end - worst.procEnd) } };
}

function lcpParts() {
  const res = lcp.url && performance.getEntriesByName(lcp.url, "resource")[0];
  const reqStart = Math.max(ttfb, res ? res.requestStart || res.startTime : 0);
  const resEnd = Math.max(reqStart, res ? res.responseEnd : 0);
  return { ttfb: Math.round(ttfb), loadDelay: Math.round(reqStart - ttfb),
    loadDuration: Math.round(resEnd - reqStart),
    renderDelay: Math.round(Math.max(lcp.startTime, resEnd) - resEnd) };
}

addEventListener("visibilitychange", () => {
  if (document.visibilityState !== "hidden" || !lcp) return;
  navigator.sendBeacon("/collect", JSON.stringify({
    page: location.pathname,
    lcp: Math.round(lcp.startTime),
    lcpElement: lcp.url ? lcp.url.split("/").pop() : lcp.element?.tagName,
    lcpParts: lcpParts(),
    cls: Number(cls.toFixed(3)),
    ...worstInteraction(),
  }));
});

02. Step 1: record the baseline and profile the click

A lab measurement is only useful when the conditions are fixed. measure.mjs opens the page in headless Chromium at a phone-sized viewport (412 × 823 CSS pixels, device pixel ratio 1.75), throttles it through the DevTools protocol — 150 ms of added latency per request, about 1.6 Mbit/s down, 750 kbit/s up and a 4× CPU slowdown, the figures of Lighthouse's default mobile profile applied DevTools-style, which is cruder than a real network — waits for the network to go quiet, clicks both buttons like a visitor, then navigates away so rum.js sends its beacon. It repeats this three times and keeps the median, because one run is an anecdote.

JavaScript · measure.mjs
// Lab run: a scripted visit under fixed throttling, read back through rum.js.
import { mkdirSync, writeFileSync } from "node:fs";
import { chromium } from "playwright";

const page = process.argv[2] ?? "storefront";
const runs = Number(process.argv[3] ?? 3);
const base = "http://127.0.0.1:8901";
const median = (xs) => [...xs].sort((a, b) => a - b)[Math.floor(xs.length / 2)];
const beacons = async () => (await fetch(`${base}/collected.json`)).json();

const browser = await chromium.launch();
const results = [];
for (let i = 1; i <= runs; i++) {
  const context = await browser.newContext({
    viewport: { width: 412, height: 823 }, deviceScaleFactor: 1.75,
  });
  const tab = await context.newPage();
  const cdp = await context.newCDPSession(tab);
  await cdp.send("Network.enable");
  await cdp.send("Network.emulateNetworkConditions", {
    offline: false, latency: 150,                 // ms added to each request
    downloadThroughput: (1600 * 1024) / 8,        // 1.6 Mbit/s in bytes/s
    uploadThroughput: (750 * 1024) / 8,
  });
  await cdp.send("Emulation.setCPUThrottlingRate", { rate: 4 });

  await tab.goto(`${base}/${page}/`, { waitUntil: "networkidle" });
  await tab.waitForTimeout(1000);                 // the visitor reads, then clicks
  await tab.click("#add");
  await tab.click("#dispatch");
  await tab.waitForTimeout(1000);
  const seen = (await beacons()).length;
  await tab.goto("about:blank");                  // hides the page: beacon fires
  let all = await beacons();
  for (let t = 0; all.length === seen && t < 50; t++) {
    await new Promise((r) => setTimeout(r, 100));
    all = await beacons();
  }
  if (all.length === seen) throw new Error("no beacon: check the page console");
  const b = all.at(-1);
  results.push(b);
  console.log(`run ${i}: LCP ${b.lcp} ms (${b.lcpElement})`,
    `CLS ${b.cls}  INP ${b.inp} ms`);
  await context.close();
}
await browser.close();

const summary = {
  page, runs: results,
  median: {
    lcp: median(results.map((r) => r.lcp)),
    cls: median(results.map((r) => r.cls)),
    inp: median(results.map((r) => r.inp)),
  },
};
mkdirSync("results", { recursive: true });
writeFileSync(`results/${page}.json`, JSON.stringify(summary, null, 2));
console.log("median", JSON.stringify(summary.median));
console.log("last run, LCP parts", JSON.stringify(results.at(-1).lcpParts));
console.log("last run, INP parts", JSON.stringify(results.at(-1).inpParts));
Terminal · start the server once, then measure the slow page
node server.mjs > server.log &   # keep it running for the whole lab
node measure.mjs storefront 3
Illustrative output — baseline (timings are machine-dependent)
run 1: LCP 3636 ms (hero.png) CLS 0.111  INP 432 ms
run 2: LCP 4516 ms (hero.png) CLS 0.111  INP 432 ms
run 3: LCP 3592 ms (hero.png) CLS 0.111  INP 432 ms
median {"lcp":3636,"cls":0.111,"inp":432}
last run, LCP parts {"ttfb":4,"loadDelay":911,"loadDuration":2658,"renderDelay":19}
last run, INP parts {"inputDelay":3,"processing":424,"presentation":5}

All three Core Web Vitals miss the "good" thresholds (LCP 2.5 s, CLS 0.1, INP 200 ms): LCP and INP land in "needs improvement", and CLS sits just above 0.1. Read the sub-parts before touching anything, because they name the cause:

  • LCP load delay of roughly 0.9 s: the image request starts only after the 700 ms stylesheet arrives and layout shows the lazy image is on screen.
  • LCP load duration of roughly 2.6 s: a 466 KB file for a slot about 350 CSS pixels wide, over a slow link.
  • CLS from one shift: the image arrives with no reserved box and pushes the text, list and buttons down by its full height.
  • INP processing of about 425 ms: the click handler blocks for 300 ms and 120 ms before the browser can paint the new badge.

That is the field side too. Open http://127.0.0.1:8901/storefront/ in your own browser, click Add to cart, switch to another tab, and look at server.log: the BEACON line is the same JSON a real visitor would send, without throttling, so its numbers are usually smaller. Lab runs are repeatable; field beacons show real devices.

The beacon says what is slow: about 430 ms of processing after the click. It cannot say which code ran. That is a profiler's job. profile.mjs loads the page, starts V8's sampling CPU profiler through the DevTools protocol (the profiler behind the JavaScript flame chart in the Performance panel), clicks Add to cart and stops. The profiler notes the call stack at short, regular intervals, so adding up the samples shows where the time went. No throttling is needed, because the question is where the time goes, not how long the visit takes. Predict before you run it: which file and line will the hottest entry point to?

JavaScript · profile.mjs
// Records one click with the V8 CPU profiler and prints the hottest functions.
import { chromium } from "playwright";

const page = process.argv[2] ?? "storefront";
const browser = await chromium.launch();
const tab = await browser.newPage();
await tab.goto(`http://127.0.0.1:8901/${page}/`, { waitUntil: "networkidle" });
const cdp = await tab.context().newCDPSession(tab);
await cdp.send("Profiler.enable");
await cdp.send("Profiler.start");
await tab.click("#add");
await tab.waitForTimeout(1000);
const { profile } = await cdp.send("Profiler.stop");
await browser.close();

// Each sample names the node on top of the stack; charge it the time since the
// previous sample. Native frames (no url) are charged to their JavaScript caller.
const nodes = new Map(profile.nodes.map((n) => [n.id, n]));
const parent = new Map();
for (const n of profile.nodes) for (const c of n.children ?? []) parent.set(c, n);
const where = ({ callFrame: f }) => {
  const file = new URL(f.url).pathname.slice(1);
  return `${f.functionName || "(anonymous)"} ${file}:${f.lineNumber + 1}`;
};
const self = new Map();
profile.samples.forEach((id, i) => {
  let n = nodes.get(id);
  while (n && !n.callFrame.url) n = parent.get(n.id);
  if (!n) return;                       // idle, garbage collection, the browser
  const caller = parent.get(n.id);
  const key = caller?.callFrame.url ? `${where(n)} <- ${where(caller)}` : where(n);
  self.set(key, (self.get(key) ?? 0) + profile.timeDeltas[i] / 1000);
});
for (const [key, ms] of [...self].sort((a, b) => b[1] - a[1]).slice(0, 3)) {
  console.log(`${String(Math.round(ms)).padStart(5)} ms  ${key}`);
}
Terminal · the server is still running
node profile.mjs storefront
Illustrative output — the milliseconds vary; the functions and lines should match
  413 ms  blockFor shared/block.js:2 <- (anonymous) storefront/app.js:9
    6 ms  (anonymous) storefront/app.js:9

Almost all of the time is in blockFor, called from the anonymous function that starts on line 9 of storefront/app.js: the Add to cart listener. In a real app the same report names your own slow function, such as a shipping-rate calculation, and the caller tells you which handler to restructure. To see it by hand, open the page in Chrome, record in the Performance panel while you click, and find the long task under the click in the Main track.

03. Step 2: fix the hero image and the layout shift

Write the fixed page. It applies the fixes from the LCP lesson in one edit: the six lines of CSS move inline, so nothing blocks the first paint; the hero becomes the 800-pixel file, which still covers a 350-pixel slot at a 2× screen density; a preload with fetchpriority="high" starts the request with the HTML; loading="lazy" goes, because this image is in the viewport; and width/height reserve its box.

HTML · www/storefront-fixed/index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Estuary Store</title>
  <link rel="preload" as="image" href="../hero-800.png" fetchpriority="high">
  <style>
    body { font-family: sans-serif; margin: 2rem; max-width: 800px; }
    h1 { font-size: 1.8rem; margin-bottom: 1rem; }
    img { display: block; max-width: 100%; height: auto; margin-bottom: 1rem; }
    .actions { display: flex; flex-wrap: wrap; align-items: center; gap: 1rem; }
    button { padding: 0.5rem 1rem; font-size: 1rem; cursor: pointer; }
    #badge { font-weight: bold; background: #e2e8f0; padding: 0.2rem 0.6rem; }
  </style>
</head>
<body>
  <h1>Estuary Fine Goods</h1>
  <img src="../hero-800.png" width="800" height="560" fetchpriority="high"
       alt="Estuary at dusk">
  <p>Hand-thrown mugs, linen and oak boards from the estuary workshops.
    Free delivery on orders over £50.</p>
  <ul>
    <li>Stoneware mug — £18</li>
    <li>Linen tea towel — £12</li>
    <li>Oak serving board — £45</li>
    <li>Rope doorstop — £22</li>
    <li>Beeswax candle — £9</li>
  </ul>
  <div class="actions">
    <button id="add">Add to cart</button>
    <button id="dispatch">Prepare dispatch</button>
    <span id="badge">0</span>
    <p id="status"></p>
  </div>
  <script type="module" src="app.js"></script>
  <script type="module" src="../rum.js"></script>
</body>
</html>
Terminal · confirm the server returns the new markup
curl -s http://127.0.0.1:8901/storefront-fixed/ | grep -E "preload|hero-800"
Expected output
  <link rel="preload" as="image" href="../hero-800.png" fetchpriority="high">
  <img src="../hero-800.png" width="800" height="560" fetchpriority="high"

width and height are the whole layout-shift fix: the browser derives the aspect ratio from them and, with the height: auto rule, reserves a correctly sized box before any image bytes arrive, so the image landing no longer pushes the content below. In a real codebase, inlining all CSS is rarely right; the equivalent is inlining the critical CSS and loading the rest without blocking, as the unblocking lesson shows.

04. Step 3: let the handlers paint

Reorganise each handler around the next paint, as in the INP lesson: update what the visitor sees first, yield so the browser can paint it, then do the rest in chunks. scheduler.yield() is used where the browser has it, with a setTimeout fallback elsewhere.

Note where blockFor comes from: shared/block.js, a module that only defines a function. Suppose it had been exported from storefront/app.js instead, and the fixed page imported it from there. Importing a module runs its top-level code once, so the browser would attach the original blocking handlers to the same buttons, and the fixed page would quietly keep the slow behaviour.

JavaScript · www/storefront-fixed/app.js
import { blockFor } from "../shared/block.js";

const yieldToPaint = globalThis.scheduler?.yield
  ? () => globalThis.scheduler.yield()
  : () => new Promise((r) => setTimeout(r, 0));

const add = document.getElementById("add");
const dispatch = document.getElementById("dispatch");
const badge = document.getElementById("badge");
const status = document.getElementById("status");
let count = 0;

add.addEventListener("click", async () => {
  count += 1;
  badge.textContent = String(count);
  status.textContent = "Added to cart";
  await yieldToPaint();         // paint badge and status first
  blockFor(300);                // shipping rates, after the paint
  await yieldToPaint();         // let any queued input run between the chunks
  blockFor(120);                // analytics and storage
});

dispatch.addEventListener("click", async () => {
  status.textContent = "Dispatching…";
  await yieldToPaint();         // paint status first
  blockFor(240);
  status.textContent = "Dispatched";
});

The total work is unchanged: 420 ms still runs after a click, and node profile.mjs storefront-fixed shows blockFor with about the same time as before. What changes is that the visitor sees the badge update within a frame or two, and a click that arrives during the work waits for one chunk, not the whole lot. The re-measure in step 4 is the test for this step.

05. Step 4: re-measure under the same conditions

Terminal
node measure.mjs storefront-fixed 3
Illustrative output — fixed page, same machine and settings
run 1: LCP 1248 ms (hero-800.png) CLS 0  INP 16 ms
run 2: LCP 1212 ms (hero-800.png) CLS 0  INP 8 ms
run 3: LCP 1212 ms (hero-800.png) CLS 0  INP 8 ms
median {"lcp":1212,"cls":0,"inp":8}
last run, LCP parts {"ttfb":26,"loadDelay":155,"loadDuration":1017,"renderDelay":14}
last run, INP parts {"inputDelay":2,"processing":1,"presentation":5}

Check that the sub-parts moved, not only the totals. Load delay fell from about 900 ms to under 200 ms because the request now starts with the HTML; load duration fell from about 2.6 s to about 1 s because the file is 137 KB instead of 466 KB; CLS is 0 because the box was reserved; and INP processing fell to a few milliseconds because the handler paints before it works. If a total improves but its dominant sub-part does not, the fix addressed the wrong slice — re-read the baseline breakdown before changing anything else.

06. Step 5: make the result stick with a budget

A result nobody defends decays. budget-check.mjs reads the median from a results file and exits non-zero when any metric is over budget, which is the signal a CI job blocks a merge on. The budgets below are the "good" thresholds; a team may agree tighter ones.

JavaScript · budget-check.mjs
import { readFileSync } from "node:fs";

const reportPath = process.argv[2] ?? "results/storefront-fixed.json";
const { median } = JSON.parse(readFileSync(reportPath, "utf8"));

// The "good" thresholds; a team can set tighter numbers than these.
const budgets = { lcp: 2500, cls: 0.1, inp: 200 };
let breaches = 0;

for (const [metric, budget] of Object.entries(budgets)) {
  const value = median[metric];
  const ok = typeof value === "number" && value <= budget; // missing = fail
  if (!ok) breaches += 1;
  console.log(`${ok ? "pass" : "FAIL"} ${metric} ${value} (budget ${budget})`);
}

console.log(breaches ? `budget: ${breaches} breach(es)` : "budget: OK");
process.exit(breaches ? 1 : 0);

Test the gate itself on numbers you know before trusting it with real ones. Predict which line fails for this file, then run it:

Terminal · a fixed results file
echo '{"median":{"lcp":2600,"cls":0.05,"inp":180}}' > results/sample.json
node budget-check.mjs results/sample.json; echo "exit code $?"
Expected output
FAIL lcp 2600 (budget 2500)
pass cls 0.05 (budget 0.1)
pass inp 180 (budget 200)
budget: 1 breach(es)
exit code 1
Terminal · run the gate against both results
node budget-check.mjs results/storefront.json; echo "exit code $?"
node budget-check.mjs results/storefront-fixed.json; echo "exit code $?"
kill %1   # stop the server when you are done
Illustrative output — your values differ; the pass and FAIL pattern should match
FAIL lcp 3636 (budget 2500)
FAIL cls 0.111 (budget 0.1)
FAIL inp 432 (budget 200)
budget: 3 breach(es)
exit code 1
pass lcp 1212 (budget 2500)
pass cls 0 (budget 0.1)
pass inp 8 (budget 200)
budget: OK
exit code 0

In CI, run the server, measure.mjs and budget-check.mjs on every pull request, and keep the budgets in the repository so changing them is a reviewed change. Treat a flaky gate as a bug to fix, not a warning to mute. The loop is complete when a deliberately re-broken page, for example the fixed page with loading="lazy" put back, fails the gate before a human sees it.

07. Troubleshooting

08. Check your understanding

Practice check · 3 questions

Reading the loop

Three checks on the lab you just ran.

Q1. Suppose blockFor were exported from storefront/app.js. Why import it from shared/block.js?
Q2. Why do width and height on the hero image remove the layout shift?
Q3. Why does measure.mjs navigate away after clicking, instead of reading rum.js at once?
Practice only: not graded, not saved, not evidence.

09. Apply it

Stretch goals on the same storefront, in rough order of value:

  1. Add a "Show 180 reviews" feature that dynamically imports a heavy module, and extend the budget check with an initial-route JavaScript limit (sum the .js resource sizes in measure.mjs) so the split is enforced.
  2. Cross-check with Lighthouse: run npx [email protected] http://127.0.0.1:8901/storefront/ --only-categories=performance --output=json --output-path=lh.json against both pages (it needs Chrome installed, or CHROME_PATH pointing at a Chrome binary), and confirm that lcp-discovery-insight, render-blocking-insight and image-delivery-insight point at the same causes your sub-parts did.
  3. Serve the hero as AVIF or WebP with srcset and sizes, and record the change in load duration.
  4. Replace rum.js with the web-vitals beacon from the field-data lesson, tag beacons with a fake release, put one fault back, and use the beacons — not the source diff — to name what regressed.

10. Review prompt

Without looking back: which three metrics made up your baseline, and which sub-part dominated each? What could the CPU profile tell you that the INP sub-parts could not? What did each fix target — load delay, load duration, layout shift or processing time? Why do width and height fix CLS while preload and fetchpriority shorten LCP? Why must a module you import for a helper be free of side effects? What does the budget check read, and what exactly does it do on a breach? And why compare like with like when re-measuring?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check