Frontend Performance and Rendering Optimization Questions
Making web pages and single-page apps fast: Core Web Vitals (LCP, INP, CLS) and page-speed metrics, the critical rendering path, reflow, repaint, forced synchronous layout and compositing, and diagnosing loading and rendering bottlenecks with browser DevTools, long-task traces and field data. Covers bundle size, code splitting, tree shaking and lazy loading, JavaScript parse and compile cost, script loading (async, defer), resource hints and fetch priority, HTTP/2 and HTTP/3 loading trade-offs, image and web-font delivery, critical CSS, a page's own browser caching (Cache-Control, fingerprinted filenames) and service-worker caching of a web app's assets, offloading work to Web Workers, smooth animation on the compositor, list virtualization and React re-render optimization, browser memory leaks and garbage-collection jank, third-party script impact, loading WebAssembly modules, rendering-strategy trade-offs for speed (CSR, SSR, SSG, streaming and partial hydration), and measuring and defending speed: user timing, real user monitoring against synthetic tests, performance budgets in CI, regression investigation and performance targets across teams. Server-side and system latency, CDN and edge caching, distributed caches, general state-management design, and design-system or visual-design decisions are covered elsewhere.
Set a realistic performance budget for a mid-sized SPA whose home page must hit an LCP of 2.5 seconds. Give numbers for the budget lines you would track, say how you derived them, and explain what happens when a change breaks one.
Sample Answer
Direct answer
Work backwards from the target. The 2.5 s figure is a field goal: web.dev says "LCP should occur within 2.5 seconds of when the page first starts loading", judged at the 75th percentile of real page loads (the value that 75% of visits are at or below). A budget enforced in CI is a lab test on one fixed, deliberately slow profile, so set the lab LCP budget tighter than 2.5 s (here 2.0 s) to leave room for users slower than your test profile. Then split that time (a "hop" is one request-response round trip; hops that depend on each other form a serial chain, and each one pays the full latency): a fixed cost for network round trips, a CPU allowance, and whatever remains is time for transferring bytes, which converts into a byte budget by multiplying by the profile's bandwidth. Finally split the bytes between HTML, JavaScript and the LCP image.
For a client-rendered SPA home page tested on a 1.6 Mbit/s, 150 ms-latency profile, that gives:
| Budget line | Value | Where it comes from |
|---|---|---|
| Lab LCP on the test profile | 2000 ms | 2500 ms target minus 500 ms headroom (a judgment call) |
| Serial requests before the LCP image can start | 3 (HTML, then JS, then image) | how a client-rendered page discovers its hero image: the HTML holds only an empty shell, the script builds the <img>, and only then can the image request start |
| Critical-path bytes in total | 230 kB | derived below |
| of which HTML, compressed | 15 kB | allocation |
| of which LCP image | 80 kB | allocation |
| of which critical JavaScript, compressed | 135 kB | the remainder |
| CLS (cumulative layout shift, how much visible content jumps) | 0.1 or less | web.dev: "pages should maintain a CLS of 0.1. or less" |
| INP (Interaction to Next Paint, how long the page takes to respond visually to a click or key press) | 200 ms or less, field only | web.dev: "pages should have a INP of 200 milliseconds or less" |
INP has no lab byte budget: a lab script exercises only the interactions you wrote, so INP is tracked from real users (the field) and a regression there is a signal to add a lab scenario, not to trust a lab number.
The derivation, step by step
Assumptions: bandwidth 1.6 Mbit/s = 200,000 bytes per second = 200 bytes per millisecond (1 kB = 1000 bytes throughout); latency 150 ms per request; 3 serial requests; a 400 ms allowance for parsing, running JavaScript and painting on a slow device. The 150 ms, 1.6 Mbit/s and 400 ms values are choices for the test profile, not facts about your users; replace them with your own RUM percentiles and a profile of your own app.
- Fixed latency: 3 x 150 ms = 450 ms.
- Time left for bytes: 2000 - 450 - 400 = 1150 ms.
- Bytes that fit: 1150 ms x 200 bytes/ms = 230,000 bytes = 230 kB.
- Split: 15 kB HTML + 80 kB image + 135 kB JS = 230 kB. JavaScript gets the remainder because it is the line teams grow.
- Cross-check: 230,000 bytes / 200,000 bytes per second = 1.15 s, and 450 + 1150 + 400 = 2000 ms.
The same arithmetic prices a change. Every 1 kB on the critical path costs 5 ms, so 100 kB of JavaScript costs 100,000 / 200,000 = 0.5 s.
Checking that the model is not fiction
The model is only useful if a real browser agrees with it. A page is served from a local server with Chromium's network emulation set to the profile above (via the Chrome DevTools Protocol, the interface DevTools uses to control the browser). It is client-rendered: an empty HTML shell, a script padded to 100, 200 and 300 kB that then inserts a 79,734-byte hero image, which is the page's only paint candidate. LCP is read from a PerformanceObserver of largest-contentful-paint entries; the model is the serial chain 3 x 150 ms + bytes / bandwidth.
// measure.mjs
import http from 'node:http';
import assert from 'node:assert/strict';
import { chromium } from 'playwright';
// Test profile: 1.6 Mbit/s down = 200,000 bytes/s, 150 ms latency per request.
const LATENCY_MS = 150, DOWN_BYTES_PER_S = 200000;
const JS_SIZES = [100000, 200000, 300000];
// 160x166 24-bit BMP (the LCP image): 54-byte header + 166 rows of 480 bytes = 79,734 bytes.
function makeBmp(w = 160, h = 166) {
const row = w * 3, size = 54 + row * h, b = Buffer.alloc(size);
b.write('BM'); b.writeUInt32LE(size, 2); b.writeUInt32LE(54, 10); b.writeUInt32LE(40, 14);
b.writeInt32LE(w, 18); b.writeInt32LE(h, 22); b.writeUInt16LE(1, 26); b.writeUInt16LE(24, 28); b.writeUInt32LE(row * h, 34);
for (let i = 54; i < size; i++) b[i] = (i * 31) & 255;
return b;
}
const bmp = makeBmp();
const html = Buffer.from('<!doctype html><meta charset=utf-8><title>spa</title><div id=root></div><script src="/app.js"></script>');
// Client-rendered page: the script (padded to the requested size) is what creates the hero image.
function appJs(totalBytes) {
const code = 'document.getElementById("root").innerHTML=\'<img id=hero src="/hero.bmp" width=160 height=166>\';\n/*';
return Buffer.from(code + 'x'.repeat(Math.max(0, totalBytes - code.length - 2)) + '*/');
}
let jsBytes = 0;
const server = http.createServer((req, res) => {
const path = new URL(req.url, 'http://x').pathname;
const send = (type, buf) => { res.writeHead(200, { 'content-type': type, 'content-length': buf.length, 'cache-control': 'no-store' }); res.end(buf); };
if (path === '/') return send('text/html', html);
if (path === '/app.js') return send('text/javascript', appJs(jsBytes));
if (path === '/hero.bmp') return send('image/bmp', bmp);
res.statusCode = 404; res.end();
});
await new Promise((r) => server.listen(0, r));
const port = server.address().port;
const browser = await chromium.launch();
async function lcp(js) {
jsBytes = js;
const ctx = await browser.newContext({ viewport: { width: 1280, height: 720 } });
const page = await ctx.newPage();
const cdp = await ctx.newCDPSession(page);
await cdp.send('Network.enable');
await cdp.send('Network.emulateNetworkConditions', { offline: false, latency: LATENCY_MS, downloadThroughput: DOWN_BYTES_PER_S, uploadThroughput: DOWN_BYTES_PER_S });
await page.addInitScript(() => {
window.__lcp = 0;
new PerformanceObserver((l) => { for (const e of l.getEntries()) window.__lcp = e.startTime; })
.observe({ type: 'largest-contentful-paint', buffered: true });
});
await page.goto(`http://localhost:${port}/`, { waitUntil: 'load' });
await page.waitForFunction(() => window.__lcp > 0, null, { timeout: 30000 });
await page.waitForTimeout(300);
const v = await page.evaluate(() => window.__lcp);
await ctx.close();
return Math.round(v);
}
// Serial-chain model: three requests one after another (HTML, then JS, then image), each paying the latency,
// plus all the bytes at the profile's bandwidth.
const model = (js) => 3 * LATENCY_MS + ((html.length + js + bmp.length) / DOWN_BYTES_PER_S) * 1000;
const fastest = [];
for (const js of JS_SIZES) {
const runs = []; for (let i = 0; i < 3; i++) runs.push(await lcp(js));
runs.sort((a, b) => a - b);
fastest.push(runs[0]); // load on the host only ever makes a run slower, so the fastest run is the one to compare
console.log(`js ${js / 1000} kB: LCP runs ${runs.join(', ')} ms | model ${Math.round(model(js))} ms`);
const off = runs[0] - model(js);
assert.ok(off >= -50 && off <= 140, `fastest run ${runs[0]} is ${Math.round(off)} ms from model ${Math.round(model(js))}, outside -50..+140`);
}
// 100 kB more critical JS costs 100,000 / 200,000 B/s = 0.5 s.
const step = (fastest[2] - fastest[0]) / 2;
console.log(`measured cost of +100 kB of critical JS: ${Math.round(step)} ms (model: ${(100000 / DOWN_BYTES_PER_S) * 1000} ms)`);
assert.ok(Math.abs(step - 500) <= 60, `slope off: ${step}`);
await browser.close(); server.close();
console.log('ALL CHECKS PASSED');
Run in the Playwright 1.48.2 image (Chromium, three runs per size; the run values are one sample, and the assertion compares the fastest run of each size with the model, because load on the host only ever makes a run slower), it printed:
js 100 kB: LCP runs 1375, 1383, 1384 ms | model 1349 ms
js 200 kB: LCP runs 1878, 1892, 1899 ms | model 1849 ms
js 300 kB: LCP runs 2391, 2394, 2396 ms | model 2349 ms
measured cost of +100 kB of critical JS: 508 ms (model: 500 ms)
ALL CHECKS PASSED
In this setup the fastest measured LCP sat about 15 to 65 ms above the model on a quiet host (rendering and paint), and each extra 100 kB cost about 500 to 510 ms, as the arithmetic says. On a heavily loaded host the typical run came out 100 to 200 ms above the model, which is why the check uses the fastest of three runs and allows up to 140 ms above the model. That validates the transfer part of the model on this synthetic page. It does not validate the 400 ms CPU allowance, which depends on your code and devices; this run used no CPU throttling, and three runs per size on one machine is evidence for the slope, not a guarantee for any other page. The check does react to a wrong model. With the emulated bandwidth doubled in the listing (downloadThroughput: DOWN_BYTES_PER_S * 2) and the model unchanged, the first size prints and the assertion fails, and a model that counts two hops instead of three (2 * LATENCY_MS) fails the same check with the fastest run about 180 ms above it:
js 100 kB: LCP runs 927, 927, 928 ms | model 1349 ms
AssertionError [ERR_ASSERTION]: fastest run 927 is -422 ms from model 1349, outside -50..+140
Sizes: the model counts the bytes that cross the wire. This demo server sends the script and image uncompressed, so raw size and wire size are the same. A real server compresses text, so the budget table and budget.mjs count the gzip size of HTML and JavaScript (the compressed bytes that cross the wire) and the file size of the already-compressed image. Apply the budget to what your server actually sends, not to the size on disk.
What happens when a change breaks a budget line
A build step measures the files on the critical path and compares them with the budget:
// budget.mjs
import fs from 'node:fs';
import path from 'node:path';
import zlib from 'node:zlib';
const cmd = process.argv[2];
// ---- derive: work backwards from the LCP target with the test profile's numbers ----
const P = { latencyMs: 150, bytesPerMs: 200, hops: 3, cpuReserveMs: 400, labLcpMs: 2000, fieldLcpMs: 2500 };
const budget = (() => {
const fixedMs = P.hops * P.latencyMs; // 3 x 150 = 450
const transferMs = P.labLcpMs - fixedMs - P.cpuReserveMs; // 2000 - 450 - 400 = 1150
const totalBytes = transferMs * P.bytesPerMs; // 1150 ms x 200 B/ms = 230,000
const html = 15000, image = 80000, js = totalBytes - html - image; // JS gets the remainder: 135,000
return { fixedMs, transferMs, totalBytes, html, image, js };
})();
if (cmd === 'derive') {
console.log(`fixed latency ${P.hops} x ${P.latencyMs} = ${budget.fixedMs} ms`);
console.log(`transfer time ${P.labLcpMs} - ${budget.fixedMs} - ${P.cpuReserveMs} = ${budget.transferMs} ms`);
console.log(`critical bytes ${budget.transferMs} ms x ${P.bytesPerMs} B/ms = ${budget.totalBytes} B`);
console.log(`split: html ${budget.html} + image ${budget.image} + js ${budget.js} = ${budget.html + budget.image + budget.js} B`);
}
// ---- gen: write a stand-in build output so the check has something to measure ----
// pseudoJs builds repetitive, JS-looking text from a seeded random generator, so gzip shrinks it by a stable, realistic-ish factor.
function pseudoJs(seed, targetRaw) { // deterministic, JS-like text
let s = seed >>> 0; const rnd = () => (s = (Math.imul(s, 1664525) + 1013904223) >>> 0) / 2 ** 32;
const words = ['const', 'function', 'return', 'value', 'state', 'props', 'render', 'effect', 'items', 'map', 'filter', 'x', 'y', 'if', 'else'];
let out = '';
while (out.length < targetRaw) out += `${words[(rnd() * words.length) | 0]}_${(rnd() * 5000) | 0}(${words[(rnd() * words.length) | 0]}, ${(rnd() * 1e6) | 0});\n`;
return out;
}
if (cmd === 'gen') {
const dir = process.argv[3], extraKb = Number(process.argv[4] || 0);
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, 'index.html'), '<!doctype html><div id=root></div><script src=vendor.js></script><script src=main.js></script>');
fs.writeFileSync(path.join(dir, 'vendor.js'), pseudoJs(1, 280000));
fs.writeFileSync(path.join(dir, 'main.js'), pseudoJs(2, 100000 + extraKb * 1000));
fs.writeFileSync(path.join(dir, 'lazy-reports.js'), pseudoJs(3, 400000)); // lazy chunk: not on the critical path
fs.writeFileSync(path.join(dir, 'hero.bmp'), Buffer.alloc(79734, 7));
fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify({ html: 'index.html', js: ['vendor.js', 'main.js'], lcpImage: 'hero.bmp' }));
}
// ---- check: fail the build when a critical-path line is over budget ----
if (cmd === 'check') {
const dir = process.argv[3];
const m = JSON.parse(fs.readFileSync(path.join(dir, 'manifest.json'), 'utf8'));
const gz = (f) => zlib.gzipSync(fs.readFileSync(path.join(dir, f)), { level: 9 }).length;
const lines = [
['html (gzip)', gz(m.html), budget.html],
['critical JS (gzip)', m.js.reduce((a, f) => a + gz(f), 0), budget.js],
['LCP image (bytes)', fs.statSync(path.join(dir, m.lcpImage)).size, budget.image],
];
let failed = false;
for (const [name, actual, limit] of lines) {
const over = actual > limit;
failed ||= over;
console.log(`${over ? 'FAIL' : 'ok '} ${name.padEnd(20)} ${String(actual).padStart(7)} / ${limit} B (${((actual / limit) * 100).toFixed(0)}%)${over ? ` over by ${actual - limit} B = ${((actual - limit) / P.bytesPerMs).toFixed(0)} ms of LCP on the test profile` : ''}`);
}
process.exit(failed ? 1 : 0);
}
$ node budget.mjs derive
fixed latency 3 x 150 = 450 ms
transfer time 2000 - 450 - 400 = 1150 ms
critical bytes 1150 ms x 200 B/ms = 230000 B
split: html 15000 + image 80000 + js 135000 = 230000 B
$ node budget.mjs gen dist && node budget.mjs check dist
ok html (gzip) 87 / 15000 B (1%)
ok critical JS (gzip) 120715 / 135000 B (89%)
ok LCP image (bytes) 79734 / 80000 B (100%)
$ node budget.mjs gen dist 60 && node budget.mjs check dist # a change adds 60 kB of raw code to main.js
ok html (gzip) 87 / 15000 B (1%)
FAIL critical JS (gzip) 139549 / 135000 B (103%) over by 4549 B = 23 ms of LCP on the test profile
ok LCP image (bytes) 79734 / 80000 B (100%)
The second gen call overwrites the first dist. check exits with status 0 for the first build and 1 for the second, and that exit status is what fails the CI job. The stand-in build output is generated text, so its compressed sizes are properties of that generator and not typical numbers. The lazy lazy-reports.js chunk is deliberately not counted: only the files listed in the manifest as needed for first paint are on the critical path.
The response policy matters as much as the check:
- The pull request fails with the line, the overage and the cost ("over by 4549 B = 23 ms of LCP"), so the author sees the consequence in the unit that matters.
- The author has three options, in order of preference: remove the bytes, move them off the critical path (lazy-load, defer), or ask to raise the budget. Raising it needs a written reason and a reviewer who owns performance, and it comes with a matching reduction elsewhere or an accepted LCP target change.
- A warning band (for example at 90% of a line) gives notice before the hard fail.
- Field data is the judge. After release, real-user p75 LCP, INP and CLS must stay within 2.5 s, 200 ms and 0.1. If the lab budget passes but the field does not, the profile or allowances are wrong, and you recalibrate them; if the field passes with room, ratchet the budget down (lower it to the new, smaller size so that later changes cannot quietly give the gain back).
Trade-offs and pitfalls
- The 400 ms CPU allowance and the 500 ms headroom are judgments. Re-derive them: profile the real home page under CPU throttling to replace the allowance, and use the gap between lab and field p75 to size the headroom.
- The chain length changes the byte budget. If the server puts the hero
<img>in the HTML, the image no longer waits behind the script and the chain loses a hop, which frees about 150 ms for bytes (and image and script then share bandwidth). Re-derive per page type. - Connection setup is not in the model. The three hops count one latency per request on connections that are already open, and the demo server is local. A first visit to a new origin also pays DNS, TCP and TLS round trips before its first request, so add them to the fixed cost for critical resources served from other origins.
- Compression choice. Budgets use compressed size because that is what crosses the wire; whether the server uses gzip or Brotli (two compression formats, Brotli usually smaller for text) changes the number, so measure what you deploy.
- A byte budget is a proxy. A small bundle that blocks the main thread for 800 ms still misses INP and LCP; keep the field metrics as the final authority.
Running the code
mkdir budget-demo && cd budget-demo
# put measure.mjs and budget.mjs in this folder
echo '{"type":"module"}' > package.json
docker run --rm --ulimit core=0 -v "$PWD":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy \
sh -c 'npm i playwright@1.48.2 && timeout 150 sh -c "node measure.mjs; node budget.mjs derive; node budget.mjs gen dist && node budget.mjs check dist; node budget.mjs gen dist 60; node budget.mjs check dist; true"'
Your customer-facing web app ships one large initial JavaScript bundle. Explain in plain terms what code splitting, tree shaking and lazy loading each do to cut what the user downloads up front, and when you would split by route rather than by component.
Sample Answer
Direct answer
All three shrink the JavaScript a visitor must download, parse (have the browser read the source text and turn it into something it can execute) and run before the page is usable, but at different moments. Tree shaking happens at build time and deletes code that nothing uses. Code splitting happens at build time too, but it keeps the code and cuts the bundle (the file the bundler produces, with a bundler being the build tool that merges your modules and their imports) into several chunks (smaller files). Lazy loading happens in the browser: a chunk is requested only when the app first needs it. Splitting by route (one chunk per URL or page) is the default because a visitor to the checkout page never needs the admin page's code; split by component when one heavy piece, such as a chart or a rich-text editor, sits inside a page but most visits never reach it.
What each technique does
| Technique | When it acts | What the user stops downloading up front | What it needs |
|---|---|---|---|
| Tree shaking | Build | Exports that no file imports, such as 30 unused helpers in a utility file | ES module syntax (import and export), which lets the bundler see what is used without running code |
| Code splitting | Build | Everything outside the chunk for the page being opened | A split point, usually a dynamic import() call, which loads a module on demand and returns a promise |
| Lazy loading | Run time in the browser | Chunks for features not yet used | Code that calls import() at the moment of need, with a loading state while it arrives |
web.dev says "Code splitting is a technique that seeks to minimize startup time" and that "splitting on the route or component level when using a client-side framework is a simpler approach". Bundlers such as webpack, Parcel and Rollup "allow you to split your bundles using dynamic imports".
Route or component
Pick route splitting first. It needs no judgement about individual features: URLs map to pages, and the pages rarely share heavy code. Pick component splitting for a piece that is both heavy (tens of kilobytes after gzip, a compression step the server applies) and reached by a minority of visits or only after an interaction: a chart behind a "Show chart" button, a map, a PDF exporter, a modal editor. A small component split alone makes things worse: the extra request costs more latency than the few bytes saved.
Vendor chunks and unused dependencies
- Vendor chunk. Your own code changes with every release, while third-party libraries change rarely. Putting the libraries in their own chunk with a content-hashed filename (a name that includes a hash of the file's contents, such as
vendor-3fa91c.js, so it changes only when the contents do) lets browsers keep reusing it across releases. web.dev: "Usually, third party dependencies are split into a separate vendor bundle that can be cached", and it points to webpack's SplitChunksPlugin for this. The trade-off is that one large vendor chunk is downloaded for every route, so keep route-specific libraries (the chart library) out of it. - Unused dependencies. Open the DevTools Coverage tab (Command Menu, type
coverage, run Show Coverage); Chrome's DevTools documentation says the panel "helps you find unused JavaScript and CSS code", with unused bytes in gray and used bytes in green. Cross-check with a bundle analyzer, then for each dependency ask whether the whole library is imported for one function. Replace it with a smaller one or a few lines of your own, or import only the part you need.
Worked example
The script generates synthetic modules with a seeded random generator, so the sizes below are made-up stand-ins chosen to make the arithmetic visible, not real library sizes. A utility file exports 30 unused functions plus one used helper. The checkout page uses a payments module (20 functions), the admin page uses a charts module (30 functions), and both share a small formatting module. Each route is built four ways with esbuild 0.24.0 (minified, meaning whitespace and long names are squeezed out of the output): everything in one bundle without and with tree shaking, one chunk per route, and finally a variant where the admin page loads the charts module on a click. "First load of a route" is the entry file plus that route's chunk plus the shared chunks it imports statically.
Walking the script: mulberry32 is a tiny seeded random number generator, and blob(n) uses it to make a string of n random characters, so every run produces identical "library code". lib(prefix, count, size) writes a module that exports count functions, each returning a different size-character string, which makes module size predictable: lib('util', 30, 800) is about 30 x 800 = 24,000 characters. The router files decide what each build contains: routerStatic imports every route with ordinary import statements (one bundle), routerRoute wraps each route in a dynamic import() (one chunk per route), and routerRouteLazy additionally makes the admin page load the charts module only when showChart() is called. import * as name followed by Object.values(name) reads every export, which is the trick that makes a module count as fully used, so tree shaking cannot drop any of it; the home route imports only usedHelper, so the other 30 utility functions are removable. In bundle(), the metafile is esbuild's report of which input files went into each output file and which output files import which. The helper closure(start) is not a JavaScript closure: it collects the file start plus every file it reaches through static import statements (the graph meaning of "closure"), because those must all arrive before the route can run, while dynamic import() edges are not followed. size() adds up raw bytes and gzip bytes (what the file shrinks to when compressed for transfer), and firstLoad is the lookup that finds a route's chunk by checking which input files went into it, then sums its closure with the entry's.
// What each technique removes from the first download. Modules are synthetic stand-ins with pinned sizes.
import { build, version } from 'esbuild';
import { mkdirSync, writeFileSync, rmSync } from 'node:fs';
import { gzipSync } from 'node:zlib';
// Seeded PRNG so the generated "library code" is identical on every run.
function mulberry32(a) { return () => { a |= 0; a = (a + 0x6D2B79F5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
const rand = mulberry32(42);
const blob = n => Array.from({ length: n }, () => Math.floor(rand() * 36).toString(36)).join('');
// A module exporting `count` functions, each carrying ~`size` characters of distinct data.
const lib = (prefix, count, size) => Array.from({ length: count }, (_, i) => `export function ${prefix}${i}() { return "${blob(size)}"; }`).join('\n');
const root = 'split-fixture';
rmSync(root, { recursive: true, force: true });
const w = (p, s) => { mkdirSync(`${root}/${p}`.split('/').slice(0, -1).join('/'), { recursive: true }); writeFileSync(`${root}/${p}`, s); };
w('lib/format.js', lib('fmt', 4, 800)); // used by checkout and admin
w('lib/utils.js', lib('util', 30, 800) + '\nexport const usedHelper = () => 1;'); // only usedHelper is imported
w('lib/payments.js', lib('pay', 20, 1000)); // checkout only
w('lib/charts.js', lib('chart', 30, 1000)); // admin only, needed only after a click
w('routes/home.js', `import { usedHelper } from '../lib/utils.js'; export default () => 'home' + usedHelper();`);
// `import * as` plus Object.values uses every export, so none of these libraries can be shaken away.
const useAll = (...ns) => ns.map(n => `import * as ${n} from '../lib/${n}.js';`).join(' ') + ` export default () => [${ns.map(n => `...Object.values(${n})`).join(', ')}].map(f => f()).join();`;
w('routes/checkout.js', useAll('format', 'payments'));
// Variant of admin where the chart code loads on click.
w('routes/admin.js', useAll('format', 'charts'));
w('routes/admin-lazy-chart.js', `import * as format from '../lib/format.js'; export const showChart = () => import('../lib/charts.js'); export default () => Object.values(format).map(f => f()).join();`);
const routerStatic = `import home from './routes/home.js'; import checkout from './routes/checkout.js'; import admin from './routes/admin.js';
const routes = { '/': home, '/checkout': checkout, '/admin': admin }; console.log(routes[location.pathname]());`;
const routerRoute = `const routes = { '/': () => import('./routes/home.js'), '/checkout': () => import('./routes/checkout.js'), '/admin': () => import('./routes/admin.js') };
routes[location.pathname]().then(m => console.log(m.default()));`;
const routerRouteLazy = routerRoute.replace('./routes/admin.js', './routes/admin-lazy-chart.js');
async function bundle(label, router, extra = {}) {
w('main.js', router);
const r = await build({ entryPoints: [`${root}/main.js`], bundle: true, splitting: true, format: 'esm', minify: true, write: false, outdir: 'out',
entryNames: '[name]', chunkNames: 'chunks/[name]-[hash]', metafile: true, logLevel: 'silent', ...extra });
const files = Object.fromEntries(r.outputFiles.map(f => [f.path.replace(/.*\/out\//, ''), f.contents]));
const meta = r.metafile.outputs;
// Static closure: a file plus everything it imports with import-statement (not dynamic import()).
const closure = start => { const seen = new Set(); const go = f => { if (seen.has(f)) return; seen.add(f); for (const i of meta['out/' + f]?.imports ?? []) if (i.kind === 'import-statement') go(i.path.replace('out/', '')); }; go(start); return [...seen]; };
const size = fs => ({ raw: fs.reduce((n, f) => n + files[f].length, 0), gz: fs.reduce((n, f) => n + gzipSync(files[f]).length, 0) });
return { label, files, closure, size, meta };
}
console.log('esbuild', version, '(minified, gzip level default); sizes in bytes, raw / gzip');
const noShake = await bundle('static, no tree shaking', routerStatic, { splitting: false, treeShaking: false });
const shake = await bundle('static, tree shaken', routerStatic, { splitting: false });
const route = await bundle('route-level import()', routerRoute);
const lazy = await bundle('route + on-click chart', routerRouteLazy);
const fmt = s => `${String(s.raw).padStart(6)} / ${String(s.gz).padStart(5)}`;
console.log('\nfirst load of any page');
for (const b of [noShake, shake]) console.log(` ${b.label.padEnd(26)} ${fmt(b.size(['main.js']))}`);
const firstLoad = (b, routeName) => {
const chunk = Object.keys(b.files).find(f => f.startsWith('chunks/') && b.meta['out/' + f] && Object.keys(b.meta['out/' + f].inputs).some(i => i.endsWith(`routes/${routeName}.js`)));
return b.size([...new Set([...b.closure('main.js'), ...b.closure(chunk)])]);
};
console.log('\nfirst load per route with route-level splitting (entry + that route + the shared code it imports)');
const results = {};
for (const b of [route, lazy]) for (const r of ['home', 'checkout', b === lazy ? 'admin-lazy-chart' : 'admin']) {
results[`${b.label}|${r}`] = firstLoad(b, r);
console.log(` ${b.label.padEnd(26)} /${r.padEnd(17)} ${fmt(results[`${b.label}|${r}`])}`);
}
const chartChunk = Object.keys(lazy.files).find(f => f.startsWith('chunks/') && Object.keys(lazy.meta['out/' + f].inputs).some(i => i.endsWith('lib/charts.js')));
console.log(`\n chart chunk, fetched only after the click: ${fmt(lazy.size([chartChunk]))}`);
// The claims the answer makes; the script fails if any stops being true.
const claims = [
['tree shaking removes the 30 unused utility functions (more than 20 KB)', noShake.size(['main.js']).raw - shake.size(['main.js']).raw > 20000],
['home route loads far less than the static bundle', results['route-level import()|home'].raw < shake.size(['main.js']).raw * 0.2],
['checkout route does not include the chart code', results['route-level import()|checkout'].raw < shake.size(['main.js']).raw * 0.6],
['on-click split makes admin smaller than route-only admin', results['route + on-click chart|admin-lazy-chart'].raw < results['route-level import()|admin'].raw * 0.5],
];
let fail = 0;
for (const [n, ok] of claims) { console.log((ok ? 'PASS ' : 'FAIL ') + n); if (!ok) fail++; }
process.exit(fail ? 1 : 0);
Run in a node:22 container, it prints:
esbuild 0.24.0 (minified, gzip level default); sizes in bytes, raw / gzip
first load of any page
static, no tree shaking 80177 / 52083
static, tree shaken 55487 / 36072
first load per route with route-level splitting (entry + that route + the shared code it imports)
route-level import() /home 405 / 385
route-level import() /checkout 24585 / 16179
route-level import() /admin 34985 / 22886
route + on-click chart /home 416 / 393
route + on-click chart /checkout 24596 / 16187
route + on-click chart /admin-lazy-chart 3925 / 2756
chart chunk, fetched only after the click: 31077 / 20134
PASS tree shaking removes the 30 unused utility functions (more than 20 KB)
PASS home route loads far less than the static bundle
PASS checkout route does not include the chart code
PASS on-click split makes admin smaller than route-only admin
Reading the numbers (raw bytes, then gzip). The second figure on each line is the size after gzip compression, which is what travels over the network when the server compresses responses; for the larger files the ratio between the two columns stays near 65% (52,083 / 80,177 = 65.0%, 22,886 / 34,985 = 65.4%), so the comparisons below hold in both columns; tiny files such as the 405-byte home route compress less because of fixed overhead. These synthetic modules are random characters, which compress worse than real code, so treat the ratio as illustrative.
- Tree shaking alone takes the single bundle from 80,177 to 55,487 bytes, 24,690 bytes removed (80,177 - 55,487; 24,690 / 80,177 = 30.8%), which is the unused utility functions. It cannot remove the payments or charts code, because routes really use it.
- Route-level
import()makes the home page's first load 405 bytes, checkout 24,585 bytes (24,585 / 55,487 = 44.3% of the tree-shaken bundle) and admin 34,985 bytes (34,985 / 55,487 = 63.1%). Nobody downloads the code of pages they have not opened. - Moving the chart behind a click cuts the admin first load to 3,925 bytes (3,925 / 55,487 = 7.1%), and the 31,077-byte chart chunk is fetched only if the user clicks. Total bytes across all chunks rise slightly (3,925 + 31,077 = 35,002 against 34,985, 17 bytes more for the extra loading code), so splitting costs a little in total to save a lot up front.
Trade-offs and pitfalls
- Request waterfalls. A waterfall is a chain of requests where each one can only start after the previous one finishes. A route chunk is requested only after the entry bundle has run. For links users are likely to follow, start fetching the chunk early (for example when the pointer hovers the link) so the wait is hidden.
- Loading states. A lazy component needs a placeholder of the right size, otherwise its arrival shifts the layout.
- Stale chunks after a deploy. If old hashed chunk files are deleted on release, an open tab that calls
import()can fail with a 404. Handle the rejection by retrying once and then reloading the page. - Too many tiny chunks. Each chunk is another request with its own latency. Split where the saving is large, and measure first-load bytes per route, as the script does, rather than splitting everything.
- The cost of JavaScript is not only download: every byte shipped must also be parsed and executed on the main thread, so unused bytes hurt slow phones even when the network is fast.
Running the code
docker run --rm -v "$PWD":/w -w /w node:22 sh -c 'echo "{\"type\":\"module\"}" > package.json && npm i esbuild@0.24.0 && node split.mjs'
Save the listing as split.mjs in the current directory first. Exit code 0 means all four checks passed.
Design a real user monitoring pipeline that tracks page-speed metrics for millions of users: what the client collects, how you sample and batch, how you aggregate and alert, and what privacy and consent constraints apply.
Sample Answer
Direct answer
Collect a handful of small numbers in the browser for each page view, send them in one batch when the page is hidden, store them as mergeable histograms (counts per bucket), and alert on the 75th percentile (p75) of each route and device segment once the segment has enough samples. Sample whole sessions rather than individual events, keep the payload free of anything that identifies a person, and treat consent as a design input rather than an afterthought.
The vocabulary: real user monitoring (RUM) means measuring performance on the devices of actual visitors, as opposed to a lab run on one machine. The numbers collected are the Core Web Vitals: LCP (Largest Contentful Paint, when the biggest visible element appears), INP (Interaction to Next Paint, how long the page takes to respond to clicks and key presses) and CLS (Cumulative Layout Shift, how much the page jumps around). web.dev gives the targets as "LCP should occur within 2.5 seconds of when the page first starts loading", "pages should have a INP of 200 milliseconds or less" and "pages should maintain a CLS of 0.1. or less", and says "a good threshold to measure is the 75th percentile of page loads, segmented across mobile and desktop devices." The 75th percentile is the value that 75% of page loads are at or below. A beacon is one small fire-and-forget HTTP request from the page carrying a batch of those numbers. Ingestion is the server side receiving and storing beacons, and a shard is one of several servers (or partitions) that each take a slice of the incoming beacons so no single machine has to handle them all.
What the client collects
| Field | Why | Careful about |
|---|---|---|
| LCP, INP, CLS values | The three vitals a segment is judged on | Use Google's open-source web-vitals library in production for exact INP and attribution; the demo below collects LCP and CLS with plain observers to stay short |
Route template such as /article/:id | Groups pages that behave alike | Never the raw URL: query strings and paths carry emails, tokens and ids |
| Device class (touch or pointer, memory bucket) | The vitals are judged per device type | Coarse buckets only, not the full user-agent string |
| Release id | Ties a regression to a deploy | None |
| Random session id, in memory only | Makes sampling consistent | Not stored in a cookie or localStorage, never sent |
CLS is a "session window" score. web.dev defines a session window as shifts "with less than 1-second in between each shift and a maximum of 5 seconds for the total window duration", reports the largest window, and notes that shifts within 500 milliseconds of user input get a hadRecentInput flag so they "can be excluded from calculations". The collector below applies exactly that.
Sampling
Sample by session, not by event: hash the in-memory session id and keep the session if the hash falls under the rate. The demo's hash is FNV-1a, a tiny non-cryptographic hash that turns a string into an evenly spread 32-bit number, so hash % 10000 < rate * 10000 keeps the chosen fraction of sessions and always makes the same decision for the same id. Every page view in a sampled session then reports, so per-session funnels stay intact, and the decision needs no stored state. Choose the rate from the smallest segment you want to alert on, because the question a segment answers is "are at least 75% of loads under the threshold?", which is a proportion. With n samples, the 95% margin on a proportion near 0.75 is about 1.960.75×0.25/n. Each factor has a job: 1.96 is the number of standard deviations around the centre of a bell curve that contains 95% of the probability; 0.75 x 0.25 is p(1 - p) for p = 0.75, which is how spread out a yes-or-no outcome (this load is under the threshold, or it is not) is; and n sits under the square root, so quadrupling the samples halves the margin:
- n = 1,000 gives 1.96×0.1875/1000=1.96×0.01369=0.0268, about plus or minus 2.7 percentage points.
- n = 100 gives 1.96×0.0433=0.0849, about plus or minus 8.5 points, too noisy to page someone. In plain terms, an observed 75% under the threshold at n = 1,000 means the true share is probably between 72.3% and 77.7%, while at n = 100 it could be anywhere from 66.5% to 83.5%. That is why the alert rules below carry a floor of 1,000 samples per window: it keeps the error bar to about 3 points, a rule of thumb rather than a guarantee.
Illustrative sizing: a route and device segment with 40,000 views an hour needs a rate of 1,000 / 40,000 = 2.5% to deliver 1,000 samples an hour, while a segment with 800 views an hour is sampled at 100%. Use a per-route rate and remember to weight by 1 / rate if you ever roll routes with different rates into one number. For example, if route A is sampled at 100% and route B at 20%, each B sample stands for 1 / 0.2 = 5 page views, so 300 A samples and 100 B samples represent 300 + 100 x 5 = 800 views, not 400.
At the whole-site level, 2,000,000 daily visitors at 6 page views each is 12,000,000 views a day; sampling 5% leaves 600,000 beacons a day, 600,000 / 86,400 = about 6.9 per second on average (assume 10 times that at peak, about 69 per second). Those are illustrative inputs, not a measurement of any site.
Batching and sending
Metrics settle late (LCP can still change while the page loads, and CLS keeps growing while the page lives), so report once, when the page becomes hidden: listen for visibilitychange on document (the browser fires it when the tab is hidden, switched away from or closed, and document.visibilityState then reads hidden) and call navigator.sendBeacon, which hands the request to the browser to finish even while the page unloads. One batch per page view of roughly 100 bytes of JSON beats a request per metric, and it never competes with the page's own requests. Expect some loss (a crash or a killed tab sends nothing) and design the dashboards to tolerate that: RUM is a statistical sample, not a ledger.
Aggregating and alerting
Do not store raw rows per page view for dashboards, and never average percentiles. Store histograms: a row per hour, route, device, release and metric holding a count per fixed bucket (for example 100 ms buckets). Histograms from different servers add together, so ingestion can be sharded, and the table size depends on the number of segments rather than on traffic: 200 routes x 2 devices x 3 metrics x 24 hours x 60 buckets is 1,728,000 counters a day however many visitors arrive (each release id live that day multiplies this, because the release is part of the row key).
The demo shows why: a fast shard (9,000 samples) has p75 2,400 ms, a slow shard (1,000 samples) has p75 5,100 ms, their average is 3,750 ms, but the true p75 of all 10,000 samples is 2,446 ms, and merging the histograms gives 2,500 ms (the upper edge of the bucket, within one 100 ms bucket of exact).
Alert rules that hold up:
- Threshold: p75 of a segment above its vital's target for two consecutive hourly windows, and only when the window has at least 1,000 samples (see the margin above).
- Regression: p75 more than a chosen percentage above the same hour one week earlier, grouped by release id so the page names the deploy.
- Pipeline health: beacon volume per segment dropping sharply, because a broken collector looks exactly like a fast site.
Privacy and consent
Design so the collector needs as little permission as possible. This is data minimisation: collect only what the question needs and nothing that identifies a person. Concretely: nothing written to the device, no cookie, no user id, no raw URL (route templates only), IP address dropped at the edge before storage, and coarse device buckets. Histograms hold no person-level data at all, so keep raw beacons only briefly (a few days) for debugging. Whether your jurisdiction still requires opt-in consent for this depends on local law and on what you store, so have counsel confirm the final design; this is an engineering decision about data minimisation, not legal advice. If your policy gates analytics behind a consent banner, start the collector only after consent, and then report the share of page views that are sampled next to every p75: visitors who decline are not a random subset, so the numbers describe the consenting population.
Worked, runnable example
The demo has six checks: (1) a page whose banner arrives late and pushes the article down sends a beacon with CLS above 0.1, (2) the same page with space reserved sends CLS 0, (3) a layout shift that follows a real click is excluded by the hadRecentInput rule, so the beacon says CLS 0 although the browser reported a shift of 0.2617, (4) two shifts 1.5 seconds apart fall in two session windows, so the beacon carries the larger one (0.1787), not their sum (0.2779), (5) the collector's own sampled function, run inside the page over 100,000 pinned ids at a 10% rate, keeps about 10,000 (the check allows three standard deviations, sqrt(100,000 x 0.1 x 0.9) x 3 = 285), and startRum refuses to start at a rate of 0 and starts at a rate of 1, and (6) merged histograms land within one bucket of the exact p75. The two layout-shift observers (layout-shift and largest-contentful-paint entries) are Chromium-family APIs, so the demo, and its CLS and LCP numbers, are Chromium measurements; the web-vitals library mentioned above is what to ship for other browsers.
// rum-demo.mjs
import http from 'node:http';
import { chromium } from 'playwright';
const BREAK = process.env.BREAK || ''; // 'noflush' (never sends), 'average' (aggregates by averaging p75s)
// ---------- client collector (served to the page) ----------
const COLLECTOR = `
function fnv1a(str) { let h = 0x811c9dc5; for (const c of str) { h ^= c.charCodeAt(0); h = Math.imul(h, 0x01000193) >>> 0; } return h; }
const sampled = (sessionId, rate) => fnv1a(sessionId) % 10000 < rate * 10000; // same session, same answer, every page view
const vitals = { lcp: null, cls: 0 };
new PerformanceObserver((l) => { vitals.lcp = l.getEntries().at(-1).startTime; }).observe({ type: 'largest-contentful-paint', buffered: true });
let win = { value: 0, first: 0, last: 0 }; // CLS = worst "session window" of shifts
new PerformanceObserver((l) => { for (const e of l.getEntries()) {
if (e.hadRecentInput) continue; // shifts right after user input do not count
if (e.startTime - win.last > 1000 || e.startTime - win.first > 5000) win = { value: 0, first: e.startTime, last: e.startTime };
win.value += e.value; win.last = e.startTime; vitals.cls = Math.max(vitals.cls, win.value);
} }).observe({ type: 'layout-shift', buffered: true });
const queue = [];
function flush() {
if (!queue.length) return;
navigator.sendBeacon('/rum', JSON.stringify(queue.splice(0))); // survives page unload, never blocks it
}
function startRum({ rate, route, release, sessionId = crypto.randomUUID() }) { // the id lives in memory only: no cookie, no storage, no user id
if (!sampled(sessionId, rate)) return false;
document.addEventListener('visibilitychange', () => {
if (document.visibilityState !== 'hidden') return;
queue.push({ route, release, device: matchMedia('(pointer:coarse)').matches ? 'touch' : 'pointer', lcp: vitals.lcp, cls: +vitals.cls.toFixed(4) });
${BREAK === 'noflush' ? '' : 'flush();'}
});
return true;
}`;
const page = (mode) => `<!doctype html><body style="margin:0"><script>${COLLECTOR}</script>
<div id="top" style="${mode === 'reserved' ? 'height:300px' : ''}"><h1>Headline</h1></div><main style="height:700px;background:#eee">Article text</main>
<button id="go" style="position:fixed;bottom:0" onclick="document.getElementById('top').style.height='300px'">Open</button>
<script>
const banner = document.getElementById('top'); window.raw = []; // raw layout-shift values, for the checks
new PerformanceObserver((l) => l.getEntries().forEach((e) => window.raw.push(e.value))).observe({ type: 'layout-shift', buffered: true });
if (['late-banner', 'reserved'].includes('${mode}')) setTimeout(() => { banner.style.height = '300px'; }, 200); // a banner arrives late and pushes the article down
if ('${mode}' === 'bursts') { setTimeout(() => { banner.style.height = '150px'; }, 200); setTimeout(() => { banner.style.height = '350px'; }, 1700); } // two shifts 1.5 s apart
window.started = startRum({ rate: 1, route: '/article/:id', release: '2026.10.1', sessionId: 'session-1' });
</script>`;
// ---------- server side: ingest, mergeable histograms, p75 ----------
const BUCKET_MS = 100;
const hist = new Map(); // key -> Map(bucketStart -> count)
function ingest(batch) { for (const b of batch) { if (b.lcp == null) continue;
const key = b.route + '|' + b.device, h = hist.get(key) || new Map(); const bucket = Math.floor(b.lcp / BUCKET_MS) * BUCKET_MS;
h.set(bucket, (h.get(bucket) || 0) + 1); hist.set(key, h); } }
function mergeHists(list) { const out = new Map(); for (const h of list) for (const [k, v] of h) out.set(k, (out.get(k) || 0) + v); return out; }
function p75FromHist(h) { const total = [...h.values()].reduce((a, b) => a + b, 0), need = Math.ceil(0.75 * total); let seen = 0;
for (const k of [...h.keys()].sort((a, b) => a - b)) { seen += h.get(k); if (seen >= need) return k + BUCKET_MS; } } // upper edge of the bucket
const nearestRank = (xs, p) => xs.slice().sort((a, b) => a - b)[Math.ceil(p * xs.length) - 1];
const received = [];
const server = http.createServer((req, res) => {
if (req.url === '/rum') { let body = ''; req.on('data', (d) => body += d); req.on('end', () => { received.push(...JSON.parse(body)); res.statusCode = 204; res.end(); }); return; }
res.setHeader('content-type', 'text/html'); res.end(page(req.url.slice(1)));
}).listen(0);
const base = `http://localhost:${server.address().port}`;
let failed = 0;
const check = (name, ok, detail) => { if (!ok) failed++; console.log(`${ok ? 'PASS' : 'FAIL'} ${name}: ${detail}`); };
// A. the client really sends a batch when the page is hidden, and CLS separates the broken page from the fixed one
const browser = await chromium.launch();
for (const path of ['late-banner', 'reserved', 'input', 'bursts']) {
const p = await (await browser.newContext({ viewport: { width: 800, height: 600 } })).newPage();
await p.goto(`${base}/${path}`); await p.waitForTimeout(600);
if (path === 'input') { await p.click('#go'); await p.waitForTimeout(300); } // a real click: the shift it causes follows user input
if (path === 'bursts') await p.waitForTimeout(1900);
const before = received.length;
// headless Chromium never hides the tab, so force visibilityState to 'hidden' and fire the event a real tab switch fires
await p.evaluate(() => { Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true }); document.dispatchEvent(new Event('visibilitychange')); });
await p.waitForTimeout(300);
const got = received.slice(before), b = got[0], raw = await p.evaluate(() => window.raw);
if (path === 'late-banner') check('beacon arrives with CLS above 0.1', got.length === 1 && b.cls > 0.1 && b.route === '/article/:id', JSON.stringify(b));
if (path === 'reserved') check('reserved space gives CLS 0 in the beacon', got.length === 1 && b.cls === 0, JSON.stringify(b));
if (path === 'input') check('a shift right after a click is excluded (hadRecentInput)', got.length === 1 && raw.length > 0 && b.cls === 0, `raw shift ${raw.map((v) => v.toFixed(4))}, beacon cls ${b && b.cls}`);
if (path === 'bursts') check('two shifts 1.5 s apart are two session windows: CLS is the larger one, not the sum', got.length === 1 && raw.length === 2 && Math.abs(b.cls - Math.max(...raw)) < 0.0005, `raw shifts ${raw.map((v) => v.toFixed(4))}, sum ${(raw[0] + raw[1]).toFixed(4)}, beacon cls ${b && b.cls}`);
await p.context().close();
}
// B. sampling, using the collector's own functions inside a page: 100,000 pinned session ids at a 10% rate
const sp = await (await browser.newContext()).newPage(); await sp.goto(`${base}/reserved`);
const { kept, atZero, atOne } = await sp.evaluate(() => { let k = 0; for (let i = 0; i < 100000; i++) if (sampled('session-' + i, 0.1)) k++;
return { kept: k, atZero: startRum({ rate: 0, route: '/x', release: 'r', sessionId: 'any' }), atOne: startRum({ rate: 1, route: '/x', release: 'r', sessionId: 'any' }) }; });
await browser.close(); server.close();
check('10% sampling keeps about 10,000 of 100,000', Math.abs(kept - 10000) < 3 * Math.sqrt(100000 * 0.1 * 0.9) && atZero === false && atOne === true, `${kept} kept (3 standard deviations = ${(3 * Math.sqrt(100000 * 0.1 * 0.9)).toFixed(0)})`);
// C. aggregation: two shards of LCP samples from a pinned generator
let x = 7; const rnd = () => (x = (Math.imul(x, 1664525) + 1013904223) >>> 0) / 2 ** 32;
const shardA = Array.from({ length: 9000 }, () => 800 + rnd() * 2000); // fast shard: 800 to 2800 ms
const shardB = Array.from({ length: 1000 }, () => 2000 + rnd() * 4000); // slow shard: 2000 to 6000 ms
const toHist = (xs) => { const h = new Map(); for (const v of xs) { const k = Math.floor(v / BUCKET_MS) * BUCKET_MS; h.set(k, (h.get(k) || 0) + 1); } return h; };
const exact = nearestRank([...shardA, ...shardB], 0.75);
const merged = BREAK === 'average' ? (p75FromHist(toHist(shardA)) + p75FromHist(toHist(shardB))) / 2 : p75FromHist(mergeHists([toHist(shardA), toHist(shardB)]));
console.log(`exact p75 ${exact.toFixed(0)} ms; shard p75s ${p75FromHist(toHist(shardA))} and ${p75FromHist(toHist(shardB))}; combined estimate ${merged.toFixed(0)} ms`);
check('merged histograms land within one bucket of the exact p75', Math.abs(merged - exact) <= BUCKET_MS, `difference ${Math.abs(merged - exact).toFixed(0)} ms, bucket ${BUCKET_MS} ms`);
process.exit(failed ? 1 : 0);
Output of one run (the lcp values in the first two lines vary between runs; every other number is deterministic or pinned, and was identical across eight runs):
PASS beacon arrives with CLS above 0.1: {"route":"/article/:id","release":"2026.10.1","device":"pointer","lcp":30.400000005960464,"cls":0.2617}
PASS reserved space gives CLS 0 in the beacon: {"route":"/article/:id","release":"2026.10.1","device":"pointer","lcp":20.900000005960464,"cls":0}
PASS a shift right after a click is excluded (hadRecentInput): raw shift 0.2617, beacon cls 0
PASS two shifts 1.5 s apart are two session windows: CLS is the larger one, not the sum: raw shifts 0.0992,0.1787, sum 0.2779, beacon cls 0.1787
PASS 10% sampling keeps about 10,000 of 100,000: 10012 kept (3 standard deviations = 285)
exact p75 2446 ms; shard p75s 2400 and 5100; combined estimate 2500 ms
PASS merged histograms land within one bucket of the exact p75: difference 54 ms, bucket 100 ms
Reading it: the first two lines show the late banner producing a layout shift of 0.2617 (above the 0.1 target) and the reserved-space page producing 0. Line three clicks a button whose handler moves the banner: the browser reports the same 0.2617 shift, but because it follows user input the collector skips it and the beacon says 0. Line four has shifts of 0.0992 and 0.1787 more than a second apart: they are separate session windows, so CLS is the worst window, 0.1787, and not the 0.2779 a plain running total would give. The demo cannot hide a tab in headless Chromium, so it overrides document.visibilityState and dispatches the visibilitychange event a real tab switch would fire; the lcp values are small because the page is tiny. Line five is the sampling check, line six the shard arithmetic from earlier, and line seven confirms the merged histogram is 54 ms from the exact p75 (inside one 100 ms bucket). Removing the hadRecentInput test makes line three fail (beacon 0.2617), and removing the one-second and five-second window rules makes line four fail (beacon 0.2779).
With BREAK=noflush (no flush() call), run once it prints:
FAIL beacon arrives with CLS above 0.1: undefined
FAIL reserved space gives CLS 0 in the beacon: undefined
FAIL a shift right after a click is excluded (hadRecentInput): raw shift 0.2617, beacon cls undefined
FAIL two shifts 1.5 s apart are two session windows: CLS is the larger one, not the sum: raw shifts 0.0992,0.1787, sum 0.2779, beacon cls undefined
PASS 10% sampling keeps about 10,000 of 100,000: 10012 kept (3 standard deviations = 285)
exact p75 2446 ms; shard p75s 2400 and 5100; combined estimate 2500 ms
PASS merged histograms land within one bucket of the exact p75: difference 54 ms, bucket 100 ms
With BREAK=average (averaging the shard p75s instead of merging histograms), the four beacon lines and the sampling line still PASS and the last two lines become:
exact p75 2446 ms; shard p75s 2400 and 5100; combined estimate 3750 ms
FAIL merged histograms land within one bucket of the exact p75: difference 1304 ms, bucket 100 ms
Each broken run exits with code 1.
Trade-offs and pitfalls
- Sampling versus collecting everything: sampling cuts ingest cost and the amount of data held about visitors, at the price of wide error bars on small segments. Raise the rate for rare routes rather than lowering the alert bar.
- Lab versus field: a lab run (Lighthouse, a Playwright script) is repeatable and catches regressions before release; RUM shows what real devices and networks do. Run both: RUM to find the problem, lab to reproduce it.
- Beacon loss: pages that crash or are frozen never report, so the slowest experiences are somewhat under-represented.
- Per-event cardinality: cardinality is the number of distinct values a field can take, so adding user id or full URL as a dimension multiplies histogram rows without helping the question being asked.
- CLS from late-loading ads or banners: the demo's fix is reserving space before content arrives.
Running the code
mkdir demo && cd demo && echo '{"type":"module"}' > package.json
npm i playwright@1.48.2 # save the listing above as rum-demo.mjs, then:
docker run --rm -v "$PWD":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy node rum-demo.mjs
# add -e BREAK=noflush or -e BREAK=average before the image name to run with that mechanism removed: FAIL lines, exit code 1
The printed output comes from the mcr.microsoft.com/playwright:v1.48.2-jammy image (headless Chromium 130.0.6723.31, aarch64 Linux container).
How do HTTP/2 and HTTP/3 change what you recommend for loading a page fast, for instance bundling, hints and request prioritization, and where does server push fit now?
Sample Answer
Direct answer
HTTP/2 and HTTP/3 make many parallel requests cheap, so the HTTP/1.1 habits that existed to avoid requests (one giant bundle, image sprites, which are many small images combined into one file, and hostname sharding, which spreads files over several hostnames to get more parallel connections) matter much less. They do not make dependency chains or bytes free. My recommendation under HTTP/2 or HTTP/3: ship tens of well-split files (a route chunk, a stable vendor chunk) instead of one monolith or hundreds of tiny modules; tell the browser about deep dependency chains up front with preload hints; mark the one or two resources that decide Largest Contentful Paint (LCP, when the main content appears) as high priority (fetchpriority="high", a hint that this fetch matters more than its neighbours); and do not use HTTP/2 server push, which Chrome disabled by default in version 106. HTTP/3 changes how the connection copes with packet loss, not what you ship.
Terms: multiplexing means many requests share one connection at the same time. Head-of-line blocking means one stalled item holds up everything queued behind it. QUIC is the transport (running over UDP) that HTTP/3 uses instead of TCP. A resource hint is a tag such as <link rel="preload"> that tells the browser about a file before it would discover it; <link rel="modulepreload"> is the version for JavaScript modules (it also parses the module and fetches its imports). Packet loss means some of the small packets that carry data over the network never arrive and must be sent again.
What each protocol changes
- HTTP/1.1: one request in flight per connection, and the browser limits connections per host. A hundred small files queue.
- HTTP/2: MDN: "Parallel requests can be made over the same connection, removing the constraints of the HTTP/1.x protocol", and it "compresses headers", removing duplicated overhead between similar requests.
- HTTP/3: "the same semantics as earlier versions of HTTP but uses QUIC instead of TCP". MDN's point: HTTP/2 runs over one TCP connection, so "packet loss detection and retransmission handled at the TCP layer can block all streams", whereas QUIC handles loss per stream, "so that if an error occurs, only the stream with data in that packet is blocked". The benefit shows on lossy links such as mobile networks; your bundle and hint strategy stays the same.
Measured: what still costs time on HTTP/2
loading-demo.mjs serves the same 100 small modules four ways over HTTPS from two servers, one speaking only HTTP/1.1 and one negotiating HTTP/2, in headless Chromium. Every response is held for 50 ms to stand in for a network round trip plus server time. Setups: one bundle file; a flat entry file that imports all 100 modules; a chain of 10 files where each imports the next; and the same chain with <link rel="modulepreload"> for all 10 listed in the HTML. It prints the median time until the last module has run, and exits non-zero unless the claims below hold. FORCE_H1=1 makes the "HTTP/2" server speak HTTP/1.1 only, and the checks then fail. The script creates a throwaway self-signed certificate with openssl (browsers speak HTTP/2 only over TLS, and ignoreHTTPSErrors lets Chromium accept that certificate), and allowHTTP1: true lets the HTTP/2 server fall back to HTTP/1.1 for clients that ask for it. Each page reports nextHopProtocol, the protocol the browser actually used (h2 or http/1.1), so the output proves which one was in play.
// loading-demo.mjs: the same 100 small modules loaded as one bundle, as a flat list, and as a 10-deep import chain,
// over HTTP/1.1 and HTTP/2. Every response is delayed by LATENCY_MS to stand in for network round trip plus server time.
import http2 from 'node:http2';
import https from 'node:https';
import zlib from 'node:zlib';
import { execSync } from 'node:child_process';
import fs from 'node:fs';
import { chromium } from 'playwright';
const LATENCY_MS = 50, RUNS = 5, N = 100, DEPTH = 10;
execSync('openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem -days 1 -subj /CN=localhost 2>/dev/null');
const tls = { key: fs.readFileSync('key.pem'), cert: fs.readFileSync('cert.pem') };
const moduleBody = (i) => Array.from({ length: 12 }, (_, k) =>
`export function f${i}_${k}(items) { return items.filter((x) => x.id % ${k + 2} === ${i % (k + 2)}).map((x) => ({ ...x, score: x.score * ${i + k} })); }`).join('\n');
const mods = Array.from({ length: N }, (_, i) => moduleBody(i));
const html = (body, head = '') => `<!doctype html><meta charset=utf-8>${head}${body}`;
const routes = {
'/bundle': () => html('<script type=module src=/b.js></script>'),
'/b.js': () => mods.join('\n') + '\nwindow.done = performance.now();',
'/flat': () => html('<script type=module src=/flat-main.js></script>'),
'/flat-main.js': () => mods.map((_, i) => `import './m${i}.js';`).join('\n') + '\nwindow.done = performance.now();',
'/chain': () => html('<script type=module src=/c0.js></script>'),
'/chain-preload': () => html('<script type=module src=/c0.js></script>', Array.from({ length: DEPTH }, (_, i) => `<link rel=modulepreload href=/c${i}.js>`).join('')),
};
for (let i = 0; i < N; i++) routes[`/m${i}.js`] = () => mods[i];
for (let i = 0; i < DEPTH; i++) routes[`/c${i}.js`] = () => (i < DEPTH - 1 ? `import './c${i + 1}.js';\n` : '') + (i === 0 ? 'window.done = performance.now();' : `export const c${i} = ${i};`);
const handler = (req, res) => {
const make = routes[req.url];
setTimeout(() => {
if (!make) { res.statusCode = 404; return res.end(); }
res.setHeader('content-type', req.url.endsWith('.js') ? 'text/javascript' : 'text/html');
res.end(make());
}, LATENCY_MS);
};
const h1 = https.createServer(tls, handler).listen(0);
// FORCE_H1=1 makes the "HTTP/2" server speak only HTTP/1.1, which must make the checks fail.
const h2 = process.env.FORCE_H1 === '1' ? https.createServer(tls, handler).listen(0) : http2.createSecureServer({ ...tls, allowHTTP1: true }, handler).listen(0);
const browser = await chromium.launch();
async function run(port, path) {
const ctx = await browser.newContext({ ignoreHTTPSErrors: true });
const page = await ctx.newPage();
await page.goto(`https://localhost:${port}${path}`);
await page.waitForFunction(() => window.done);
const r = await page.evaluate(() => ({ done: window.done, proto: performance.getEntriesByType('resource')[0].nextHopProtocol, n: performance.getEntriesByType('resource').length }));
await ctx.close();
return r;
}
const median = (xs) => [...xs].sort((a, b) => a - b)[Math.floor(xs.length / 2)];
const res = {};
console.log(`simulated delay per response: ${LATENCY_MS} ms; median of ${RUNS} loads`);
for (const [label, port] of [['HTTP/1.1', h1.address().port], ['HTTP/2 ', h2.address().port]]) {
for (const path of ['/bundle', '/flat', '/chain', '/chain-preload']) {
const rs = []; for (let i = 0; i < RUNS; i++) rs.push(await run(port, path));
res[label.trim() + path] = { ms: median(rs.map((r) => r.done)), proto: rs[0].proto, requests: rs[0].n };
console.log(`${label} ${path.padEnd(15)} ${res[label.trim() + path].ms.toFixed(0).padStart(5)} ms ${String(rs[0].n).padStart(3)} requests (${rs[0].proto})`);
}
}
await browser.close(); h1.close(); h2.close();
const sep = mods.reduce((s, m) => s + zlib.gzipSync(m).length, 0), one = zlib.gzipSync(mods.join('\n')).length;
console.log(`gzip: ${N} separate files = ${sep} B, one concatenated file = ${one} B (${(sep / one).toFixed(2)}x)`);
const R = res;
const ok = R['HTTP/2/flat'].proto === 'h2' && R['HTTP/1.1/flat'].proto === 'http/1.1'
&& R['HTTP/1.1/flat'].ms > 2 * R['HTTP/2/flat'].ms // multiplexing: many parallel requests are cheap on HTTP/2
&& R['HTTP/2/chain'].ms > R['HTTP/2/flat'].ms + 150 // a dependency chain still costs one round trip per level
&& R['HTTP/2/chain-preload'].ms < R['HTTP/2/chain'].ms / 2 // telling the browser the chain up front removes the waterfall
&& R['HTTP/2/bundle'].ms < R['HTTP/2/flat'].ms // one request still beats a hundred
&& sep > one; // and a bundle compresses better than separate files
console.log(ok ? 'PASS' : 'FAIL');
process.exit(ok ? 0 : 1);
The first command in the last section prints a sample like this (timings on one machine with simulated delay and no packet loss, so only the ordering and the round-trip counts carry over; the milliseconds shift by a few from run to run):
simulated delay per response: 50 ms; median of 5 loads
HTTP/1.1 /bundle 115 ms 1 requests (http/1.1)
HTTP/1.1 /flat 1095 ms 101 requests (http/1.1)
HTTP/1.1 /chain 595 ms 10 requests (http/1.1)
HTTP/1.1 /chain-preload 177 ms 10 requests (http/1.1)
HTTP/2 /bundle 115 ms 1 requests (h2)
HTTP/2 /flat 211 ms 101 requests (h2)
HTTP/2 /chain 599 ms 10 requests (h2)
HTTP/2 /chain-preload 116 ms 10 requests (h2)
gzip: 100 separate files = 23331 B, one concatenated file = 6998 B (3.33x)
PASS
exit=0
Reading it in round trips of 50 ms (the HTML page itself costs one):
| Setup (HTTP/2) | Sequence | Rounds | Expected | Measured |
|---|---|---|---|---|
| Bundle | HTML, then one file | 2 | 100 ms | 115 ms |
| Flat, 100 modules | HTML, entry file, then all 100 in parallel | 3 | 150 ms | 211 ms |
| Chain of 10 | HTML, then 10 files one after another | 11 | 550 ms | 599 ms |
Chain with modulepreload | HTML, then all 10 in parallel | 2 | 100 ms | 116 ms |
The expected column counts only the simulated 50 ms delays. The measured time is higher than expected in every row because it also includes real work the table does not count: the TLS handshake on a new connection, moving the bytes, and parsing and running the JavaScript. Across repeated runs on one machine the gap was roughly 15 to 90 ms, and about 120 ms for the flat page when the container was limited to one CPU; it varied from run to run, and the flat page (101 files to fetch and run) and the chain had the largest gaps.
The second command, with FORCE_H1=1, makes the "HTTP/2" server speak HTTP/1.1. Every row now reports http/1.1, the flat page takes about as long as on the HTTP/1.1 server (1,109 ms against 1,156 ms in one sample), and the script fails:
simulated delay per response: 50 ms; median of 5 loads
HTTP/1.1 /bundle 118 ms 1 requests (http/1.1)
HTTP/1.1 /flat 1156 ms 101 requests (http/1.1)
HTTP/1.1 /chain 604 ms 10 requests (http/1.1)
HTTP/1.1 /chain-preload 179 ms 10 requests (http/1.1)
HTTP/2 /bundle 115 ms 1 requests (http/1.1)
HTTP/2 /flat 1109 ms 101 requests (http/1.1)
HTTP/2 /chain 594 ms 10 requests (http/1.1)
HTTP/2 /chain-preload 186 ms 10 requests (http/1.1)
gzip: 100 separate files = 23331 B, one concatenated file = 6998 B (3.33x)
FAIL
exit=1
What it shows: on HTTP/1.1 the flat 100-module page took about 5 times as long as on HTTP/2 (1,095 ms against 211 ms), which is why bundling used to be essential. On HTTP/2 the flat page is cheap in rounds, but the chain still costs a round per level (599 ms), because the browser cannot know file 5 is needed until file 4 has arrived, and preload hints remove that wait (116 ms). The one-file bundle and the preloaded chain finished within a few milliseconds of each other (115 ms and 116 ms in the sample above), both far ahead of the flat page. The gzip line is for these synthetic, highly repetitive modules (a real application compresses less dramatically), but the direction is general: many tiny files compress worse than one larger file because each starts with an empty dictionary and carries its own overhead. The ratio printed is 23,331 / 6,998 = 3.33.
Prioritising what matters for LCP on a large page
- Make the LCP resource discoverable in the HTML, not hidden in CSS or injected by script. web.dev: "your LCP resource should be discoverable from the HTML source", and "Never lazy-load your LCP image".
- Mark it high priority.
fetchpriority="high"on the image (or on the preload if the image is a CSS background). web.dev describesfetchpriorityas relative priority and a hint: valueshigh,lowandauto. Support is recent: Chrome and Edge 102, Safari 17.2 and Firefox 132; a browser without it ignores the attribute and falls back to its default priorities, so the page must still work without it. - Lower the rest.
fetchpriority="low"on below-the-fold images and non-critical scripts, so they stop competing with the LCP image for bandwidth. Marking everything high cancels the effect. - Do not rely on the network to honour it. web.dev warns that "CDNs don't implement HTTP/2 prioritization uniformly, and similarly for HTTP/3", while the browser's own internal prioritisation still applies, so keep the hint and also keep the critical path short.
- Preload sparingly: the one hero image and the one critical font, not twenty files.
Where server push fits now
Nowhere for new work. Chrome announced it would disable HTTP/2 Server Push by default in Chrome 106, and that push "was not implemented in many HTTP/3 servers and clients"; for the part of the web that already uses HTTP/3, the same article says push had effectively been retired already. Its recommended replacements: 103 Early Hints, "a much less error-prone alternative with many of the same upsides as Push": an interim response sent before the final one, which looks like this in Chrome's documentation (103 Early Hints, then one Link header per hint, each with a rel of preconnect or preload):
103 Early Hints
Link: <https://fonts.google.com>; rel=preconnect
Link: </main.css>; rel=preload; as=style
Link: </common.js>; rel=preload; as=script
The browser decides whether to request the hinted resource (for example, skipping one it already has cached). Early Hints can start the fetch earlier than a <link rel="preload"> tag in the HTML, because that tag is only seen after the HTML itself has arrived.
Trade-offs and common wrong turns
- Concluding "HTTP/2 means no bundling": the demo's chain and the bundle's smaller size say otherwise. Keep a bounded number of chunks.
- Keeping hostname sharding from the HTTP/1.1 era: under HTTP/2 one multiplexed connection is the goal, and every extra hostname costs its own connection setup.
- Splitting into hundreds of tiny modules in production because the dev server does: it creates the flat-100 case and loses compression.
- Hinting everything: preload and high priority only help if few resources have them.
- Assuming HTTP/3 will fix a slow page: it helps recovery from packet loss; it does not shorten a long dependency chain or shrink a large bundle.
Running the code
# folder with loading-demo.mjs (above) and package.json: {"type":"module","private":true}
docker run --rm -v "$PWD":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy sh -c \
'npm i playwright@1.48.2 && node loading-demo.mjs; echo exit=$?
FORCE_H1=1 node loading-demo.mjs; echo exit=$?'
What happens in the browser, and when does the script run, for a plain script tag, an async one, a deferred one and a module script? Which would you use for a critical app bundle versus an analytics snippet?
Sample Answer
Direct answer
The browser builds the page by parsing HTML from top to bottom. A plain <script src> stops that parsing, downloads, runs, and only then lets parsing continue. async and defer download in parallel with parsing and differ in WHEN they run: async runs the moment the file is ready (pausing the parser if it is still going), defer waits until parsing is finished. A module script (type="module") is deferred by default. For the critical app bundle use type="module" (or defer); for an analytics snippet use async.
What each one does, in the order it happens
| Tag | Fetch | Runs | Order between scripts |
|---|---|---|---|
<script src> | Parser stops until it arrives | Immediately, before parsing resumes | Document order |
<script async src> | In parallel with parsing | As soon as it is available | Not guaranteed |
<script defer src> | In parallel with parsing | After the document is parsed, before DOMContentLoaded | Document order |
<script type="module" src> | In parallel; its imports are fetched too | Deferred, after parsing | Document order |
These match MDN's wording: a plain script is "fetched and executed immediately before the browser continues to parse the page"; defer scripts execute "after the document has been parsed, but before firing DOMContentLoaded event" and "in the order in which they appear in the document"; for modules, "the processing of the script contents is deferred". DOMContentLoaded is the event that fires when the HTML has been fully parsed and the deferred scripts have run.
Module scripts have extra properties. They always run in strict mode (a stricter JavaScript dialect that turns silent mistakes, such as assigning to an undeclared variable, into errors). They have their own scope: a top-level const total in a module is not a property of window, so another script cannot read it. A module fetched from another origin needs CORS (cross-origin resource sharing) headers, meaning the other server must reply with an Access-Control-Allow-Origin header that permits your page, otherwise the browser refuses to run it. The defer attribute is ignored on them because they already behave that way. Adding async to a module makes it run as soon as it and all its imports are available, like a classic async script.
Seeing it run
The page below puts all four kinds in the <head>, each served with an artificial delay, and adds a plain script tail at the end of the <body> that takes 700 ms. That slow tail keeps the parser busy after the others have arrived, which is what separates async (runs when it arrives) from defer (waits for parsing to finish). Each script records whether the paragraph that comes after it in the HTML has been parsed yet. Save this as load-order.mjs:
load-order.mjs
import http from 'node:http';
import { chromium } from 'playwright';
// Each script file reports when it runs and whether the <p id="after"> below it has been parsed yet.
const delays = { plain: 400, async: 100, defer: 250, module: 50, tail: 700 };
const page = `<!doctype html><html><head>
<script>window.log = [];</script>
<script src="/plain.js"></script>
<script async src="/async.js"></script>
<script defer src="/defer.js"></script>
<script type="module" src="/module.js"></script>
</head><body><p id="after">content after the scripts</p>
<script src="/tail.js"></script>
<script>document.addEventListener('DOMContentLoaded', () => window.log.push('DOMContentLoaded'));</script>
</body></html>`;
const server = http.createServer((req, res) => {
const name = req.url.slice(1).replace('.js', '');
if (req.url === '/') { res.setHeader('content-type', 'text/html'); return res.end(page); }
setTimeout(() => {
res.setHeader('content-type', 'text/javascript');
res.end(`window.log.push('${name} (after paragraph parsed: ' + !!document.getElementById('after') + ')');`);
}, delays[name]);
});
await new Promise(r => server.listen(0, r));
const url = `http://localhost:${server.address().port}/`;
const browser = await chromium.launch();
const p = await browser.newPage();
await p.goto(url, { waitUntil: 'load' });
const log = await p.evaluate(() => window.log);
console.log(log.join('\n'));
const expected = ['plain (after paragraph parsed: false)', 'async (after paragraph parsed: true)', 'tail (after paragraph parsed: true)', 'defer (after paragraph parsed: true)', 'module (after paragraph parsed: true)', 'DOMContentLoaded'];
if (JSON.stringify(log) !== JSON.stringify(expected)) { console.error('FAIL: unexpected order'); process.exit(1); }
await browser.close(); server.close();
The script waits for the page's load event (fired once the page and the resources it references, such as scripts and images, have finished loading) before reading the log. Run in the Playwright 1.48.2 image (Chromium), it prints these six lines on every run (six of six runs; measured with the delays 400, 100, 250, 50 and 700 ms); the delays are far enough apart that the order does not vary, though a heavily loaded machine or delays that are closer together could change which script arrives first:
plain (after paragraph parsed: false)
async (after paragraph parsed: true)
tail (after paragraph parsed: true)
defer (after paragraph parsed: true)
module (after paragraph parsed: true)
DOMContentLoaded
Reading it:
plainran while the paragraph did not exist yet: the parser was frozen on that line for its whole 400 ms download.asyncappears second because its tag comes after theplaintag in the document. Step by step: the parser reachesplainand stops; 400 ms laterplainhas downloaded and run, and parsing resumes; the parser now reaches theasynctag, whose file is only 100 ms away and may already have arrived, so it runs as soon as the browser gets to it; in these runs the parser had already moved past the paragraph by then, so the paragraph exists. The lesson: a blocking script ahead of other scripts also delays the moment those tags are reached.tailis a plain script at the end of the body: the parser is blocked on it for 700 ms, and it runs with the paragraph already parsed.deferarrived after 250 ms, long beforetailfinished, yet it ran aftertail: a deferred script waits for the end of parsing, however early it arrives. Changedefertoasyncanddeferis logged beforetail, which is the difference between the two attributes. It still ran beforeDOMContentLoaded.moduletook only 50 ms to download but ran afterdefer, because it waits in the same document-order queue; that is why a slow deferred script can hold back a fast module that follows it.DOMContentLoadedfired last.
Which to use
Critical app bundle: type="module" (or defer for a classic bundle), placed in the <head>. Putting the tag in the head lets the browser start the download immediately, and the deferred behaviour means it still does not block rendering of the HTML. The script can rely on the DOM being fully parsed, and several deferred scripts keep their relative order, which matters when one depends on another (a framework before the app). A plain script in the head would block first paint (the first moment the browser draws any part of the page) for its whole download and execution.
Analytics snippet: async. Nothing depends on it and it depends on nothing, so its order is irrelevant and it should never delay anything else. The cost to remember: it executes whenever it arrives, which can be in the middle of parsing or right when the main bundle is running, so keep the snippet small and consider starting it after the page's load event if it is not needed earlier.
Plain script: only for tiny inline code that must run before first paint, for example setting a theme class on <html> to avoid a flash of the wrong colours.
Pitfalls
asyncon a script that needs the DOM or another script: it may run before either exists. The result passes in development (fast cache) and fails in production, so it looks random.- Expecting
asyncscripts to run in order. They do not. - Moving a plain script to the bottom of
<body>was the old workaround;deferin the head is better because the download starts earlier. - Assuming
deferorasyncmakes the work free: when the script finally runs, its execution still occupies the main thread and can delay interactions.
Running the code
mkdir load-order-demo && cd load-order-demo
echo '{"type":"module"}' > package.json
npm i playwright@1.48.2
npx playwright install chromium # skip inside the mcr.microsoft.com/playwright:v1.48.2-jammy image
node load-order.mjs
Unlock Full Question Bank
Get access to all 27 Frontend Performance and Rendering Optimization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.