Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 20 min · revision 2

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

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:

Illustrative output · vite build, everything in the entry chunk (hashes and sizes vary)
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 route

Two 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:

JavaScript · main.js, static import replaced by a dynamic one
document.getElementById('show-reviews').addEventListener('click',
  async () => {
    const { renderReviews } = await import("./reviews.js");
    renderReviews(document.getElementById("reviews"));
  });
Illustrative output · vite build, and the network across one visit
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: 180

The 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:

JavaScript · the line that keeps 120 helpers alive
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 ...
  };
}
Illustrative output · the same build with and without the registry
# 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 kB

Deleting 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):

JavaScript · budget-check.mjs (the bundle half)
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);
Illustrative output · the check against both builds
# 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

Practice check · 3 questions

Budgets and splits

Three decisions from the build above.

Q1. Your budget counts "initial route JavaScript". Which files belong in it?
Q2. On a flaky connection the reviews chunk request fails. What should the click handler do?
Q3. A module keeps 120 helpers in the bundle because of one top-level `window.X = { all of them }` line. What is the smallest change that lets tree shaking drop the unused ones?
Practice only: not graded, not saved, not evidence.

08. Apply it

On a project you own (the Vite lesson sets one up from scratch):

  1. Run the production build and write down the initial-route JavaScript in raw and gzip figures.
  2. Open the bundle analyser and name the three largest contributors — dependency, feature, or data.
  3. Move one interaction-gated feature behind import(), with a pending state and a caught error.
  4. Hunt for top-level side effects in your own modules and delete the ones nothing needs; rebuild and record the difference.
  5. 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.

Sign in to mark reading complete

Prove this skill

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