JavaScript cost and the main thread · mid
JavaScript cost: bundle size, code splitting and tree shaking
JavaScript is the most expensive byte on the web because it must be downloaded, parsed, compiled and executed on the main thread, so you measure the bundle, split it by route and interaction, tree-shake unused code, and keep it from growing back.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Cost is not only download: on a low-end Android phone, parse + compile + execute of 1 MB of JS can take seconds of main-thread time, which hurts LCP (for CSR), TBT and INP.
- Measure first: a bundle analyzer (webpack-bundle-analyzer, source-map-explorer, Next.js bundle analyzer), DevTools Coverage tab for unused bytes, and size-limit in CI.
- Code splitting: route-level splitting with dynamic import() or React.lazy; component-level splitting for heavy, rarely used UI (rich editor, charts, maps). Load on interaction or idle.
- Tree shaking removes unused exports, but only with ES modules and side-effect-free code ("sideEffects": false). CommonJS dependencies and barrel files often defeat it.
- Replace heavy libraries (moment -> date-fns or Intl/Temporal, lodash -> per-function imports or native), and remove duplicate versions of the same package.
- Too many tiny chunks create request waterfalls; split at meaningful boundaries and prefetch the next likely chunk.
- Ship modern code: set browser targets (browserslist) from your real-user analytics, so you don't transpile or polyfill features your users already have; every unneeded polyfill is bytes and parse time.
- React Server Components send zero JS for server-only components; 'use client' marks the boundary where JS starts.
The red pen
Common traps: mistake → fix
Mistake: "Gzip makes bundle size irrelevant"
Fix: compression reduces transfer bytes, but the browser still parses and executes the full uncompressed code.
Mistake: "Lazy-load everything"
Fix: lazy-loading above-the-fold UI delays it; split what is not needed for the first view.
Mistake: "Tree shaking always removes unused code"
Fix: it needs ESM and no side effects; CommonJS and side-effectful modules are kept.
Easy to hard
Questions interviewers ask, easy to hard
- Why is 300 KB of JavaScript more expensive than a 300 KB image?
- Our main bundle is 1.8 MB. How do you bring it down?
- How does tree shaking work and why did importing one function pull in the whole library?
- How do you stop the bundle from growing back after you fix it?
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.