Shipping Less JavaScript: Bundle Analysis and Splitting
Read a production build honestly, split code the visitor does not need yet behind dynamic imports, keep tree shaking possible, and hold the result with a budget that fails CI.
Contentsand lesson path
On this page
- The problem: JavaScript is a rental, not a purchase
- Step 1: read what the build actually ships
- Step 2: let the interaction pull its own code
- Step 3: keep tree shaking possible
- Step 4: hold the line with a budget in CI
- Common mistakes
- Check your understanding
- Apply it
- Review prompt
Lessons of Web Performance & Core Web Vitals
- Field Data: Web Vitals, Client Errors and Real-User Monitoring Concept · 25 min
- Diagnosing LCP: Images, Fonts and the Critical Path Worked example · 25 min
- Diagnosing INP: Long Tasks and Re-renders Worked example · 25 min
- Shipping Less JavaScript: Bundle Analysis and Splitting Worked example · 20 min
- Lab: Profile, Fix and Budget a Slow Storefront Lab · 30 min
- Check: Diagnose the Trace Knowledge check · 10 questions
What you will learn
- Optimize loading with responsive modern-format images, font loading strategy, resource hints and fetch priority, HTTP caching and code splitting by route and interaction.
- Set and enforce performance budgets (initial JavaScript size, LCP, CLS) with bundle analysis and automated Lighthouse checks.
Prerequisites: How Browsers Render Pages
01. The problem: JavaScript is a rental, not a purchase
Every byte of JavaScript costs four times over: download, parse, compile to bytecode, and then execution on the main thread — and unlike an image, a script keeps costing on every visit even when cached. The HTTP cache saves only the download. Execution runs again on every page load, and parse and compile run again too unless the engine's own code cache can reuse earlier work (Chrome's V8, for example, can skip compilation from the third load of an unchanged file). That is why the heaviest-looking page is often not the slowest one, and why "ship less JavaScript" beats "ship the same JavaScript more efficiently".
A product page for a field jacket is a good example. It shows a price, a photo, an "Add to cart" button — and, folded away, a rich review viewer used by a minority of visits. Bundled naively, everything ships together. The experiments below are real builds with Vite 8.3.5 (which bundles with Rolldown), run on Node v22; the numbers are from vite build output and gzip -k, and your exact figures will differ slightly with versions.
02. Step 1: read what the build actually ships
The production build tells you the truth in six lines. What matters is not only the size but which file the initial route loads — the one index.html references, plus everything it statically imports:
dist/index.html 0.50 kB │ gzip: 0.32 kB
dist/assets/index-pu1y0oMu.js 148.11 kB │ gzip: 42.42 kB
# compressed on disk for the budget check:
# 148,110 B raw -> 41.1 kB gzipped for the initial routeTwo numbers, two audiences. The gzip figure approximates what crosses the network (servers compress on the fly); the raw figure approximates what the main thread must parse and compile, because compression is undone before the engine sees the code. Both matter and neither substitutes for the other. A bundle analyser (visualisations over the same build, offered by plugins for Vite and friends) answers the next question: which dependency contributed which region of that 148 KB. Here the answer was a 110 KB review-data module and a date library — the review viewer being code that most visits never touch.
03. Step 2: let the interaction pull its own code
Code needed only after an interaction belongs behind a dynamic import(). The bundler splits it into its own file and rewrites the call into a fetch at click time. The review viewer is the textbook case — needed on "Show 180 reviews", never before:
document.getElementById('show-reviews').addEventListener('click',
async () => {
const { renderReviews } = await import("./reviews.js");
renderReviews(document.getElementById("reviews"));
});dist/assets/index-CH0CcoLr.js 21.92 kB │ gzip: 6.75 kB
dist/assets/reviews-a80olCbP.js 109.08 kB │ gzip: 28.51 kB
network, page load: ["index-CH0CcoLr.js 200"]
network, after click: ["index-CH0CcoLr.js 200","reviews-a80olCbP.js 200"]
review items rendered: 180The initial route fell from 148 KB to 22 KB (41.1 to 6.6 KB gzipped), and the network log proves the lazy chunk was fetched only on click. Two follow-throughs keep it honest. Give the click a visible state: the fetch takes real time on a phone, so disable or label the button while the chunk loads, and handle failure — a caught error with a "try again" affordance, not a silent no-op, because a train tunnel can swallow the request. And once a feature earns its own chunk, the browser can cache it independently: hashed file names plus long-lived Cache-Control (a year, immutable) for assets, with the HTML revalidated (no-cache — check before use, not never store), mean a new deploy invalidates everything at once without re-downloading unchanged chunks.
04. Step 3: keep tree shaking possible
Splitting helps features you do not use yet; tree shaking removes exports you never use at all. Bundlers can only drop what they can prove is unused, and one pattern defeats the proof. A legacy-style helper module that publishes itself at the top level looks innocent:
export function legacyHelper0(x) { /* ... */ }
// ... 119 more exports ...
// TOP-LEVEL SIDE EFFECT that references every helper:
if (typeof window !== "undefined") {
window.__legacyCompat = {
legacyHelper0, legacyHelper1, legacyHelper2, legacyHelper3,
// ... every helper, so nothing can be proven unused ...
};
}# with the top-level window assignment:
dist/assets/index-J3E23YKV.js 40.70 kB │ gzip: 14.16 kB
# after deleting it (main.js imports one helper):
dist/assets/index-CH0CcoLr.js 21.92 kB │ gzip: 6.75 kBDeleting one line removed 7.4 kB of gzipped code (18.8 kB raw) — the 119 helpers the page never calls. That is the lesson: a bundler keeps any top-level statement it cannot prove free of side effects, and everything that statement references stays with it. Export functions individually, keep module top levels free of work, and the bundler shakes the rest — modern ones even shake a import * as ns namespace import when you use one known property, so "namespace imports defeat shaking" is no longer a safe claim to make; the registry pattern above is the reliable villain. The same reasoning applies to dependencies: a library that runs code at import time cannot be shaken safely, which is why side-effect-free packages state "sideEffects": false in their manifest — a promise that lets the bundler drop a whole unused module. A wrong promise drops code that was needed, so it belongs only on packages that really have no import-time work.
05. Step 4: hold the line with a budget in CI
Everything above decays without a guardrail: one urgent PR re-imports the review module statically and the initial route is 148 KB again, reviewed by nobody. A performance budget turns the agreement into a failing check. The shape that works: a small script in CI, run on the built output, that exits non-zero on breach — measured against the same definition every time (here: what index.html references):
import { readFileSync } from "node:fs";
import { gzipSync } from "node:zlib";
const html = readFileSync("dist/index.html", "utf8");
const files = [...html.matchAll(/assets\/[\w.-]+\.js/g)]
.map((m) => m[0]);
const kb = files.map((f) =>
gzipSync(readFileSync(`dist/${f}`)).length / 1024);
const initial = kb.reduce((a, b) => a + b, 0);
const ok = initial <= 25; // the agreed budget
console.log(ok ? "pass" : "FAIL",
"initial route JS", initial.toFixed(1), "kB gzip (budget 25 kB)");
process.exit(ok ? 0 : 1);# against the everything-included build:
FAIL initial route JS 41.1 kB gzip (budget 25 kB)
# against the split build:
pass initial route JS 6.6 kB gzip (budget 25 kB)The same idea extends to lab metrics: Lighthouse CI's assertions can fail a build when LCP or CLS breach a budget, and performance budgets cover choosing the numbers with the team. Because a single lab run wobbles with machine load, teams assert on the median of several runs in a fixed environment — the variance is real, and budget checks that flake get switched off, which is worse than no check. Keep the definition of "initial route JavaScript" written down next to the check; a budget whose definition drifts is not a budget.
06. Common mistakes
07. Check your understanding
08. Apply it
On a project you own (the Vite lesson sets one up from scratch):
- Run the production build and write down the initial-route JavaScript in raw and gzip figures.
- Open the bundle analyser and name the three largest contributors — dependency, feature, or data.
- Move one interaction-gated feature behind
import(), with a pending state and a caught error. - Hunt for top-level side effects in your own modules and delete the ones nothing needs; rebuild and record the difference.
- Commit the budget script with a number the team agreed on, and let it fail once on purpose to prove CI catches it.
09. Review prompt
Without looking back: which four costs does JavaScript incur, and which of them does the HTTP cache save? What belongs in an "initial route JavaScript" figure? What does import() change about when code is fetched, and what must the click handler add? Which pattern keeps unused exports alive even when they are never called, and why? And what makes a budget a budget rather than a note?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.