Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 37 ยท JavaScript Performance

Bundle Size and Code Splitting

Learn why JavaScript costs more than images of the same size, how compression, tree shaking and code splitting shrink bundles, and how to lazy load code.

A 300 KB JavaScript file and a 300 KB image are not equal. The image is downloaded and decoded off the main thread. The script must be downloaded, parsed, compiled and executed on the main thread, and a mid-range phone does that several times slower than a laptop. Shipping less JavaScript is therefore the most reliable way to make a page start faster.

This lesson covers what makes bundles big and the four tools you use against it: compression, minification, tree shaking and code splitting.

Transfer size versus parse size

Two numbers matter:

  • Transfer size is what travels over the network, usually compressed with gzip or Brotli.
  • Uncompressed size is what the browser must parse and run. A 100 KB gzip file can be 400 KB of JavaScript.

Compression helps the network but not the CPU. Both numbers should go down.

Compression and minification

Minification removes whitespace and comments and shortens local names. Compression (gzip, Brotli) then squeezes repeated patterns. Run both in production. Brotli typically beats gzip by 15 to 20 percent for text files.

You can measure compression right in the browser with CompressionStream:

JS Measuring gzip size

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Repetitive text compresses very well, so the gap shrinks after gzip. That is why you should judge changes by both numbers.

Where bundle weight comes from

Open a bundle analyzer (such as source-map-explorer, webpack-bundle-analyzer or the visualizer plugin for Vite) and you will usually find the same culprits:

  • A whole utility library imported for one function (import _ from "lodash" instead of one function).
  • A date or locale library shipping every locale.
  • Several libraries doing the same job (two date libraries, two HTTP clients).
  • Polyfills for browsers you no longer support.
  • Code for features that most visitors never open: admin screens, charts, rich-text editors.

Before adding a dependency, check its size on a package-size tool, and ask whether the platform already does it (fetch, Intl, URL, structuredClone, <dialog>).

Tree shaking

Tree shaking means the bundler drops exports that nothing imports. It works with ES modules (import/export), because their structure is static. It does not work reliably with CommonJS (require).

JavaScript
// utils.js
export function used() { return "kept"; }
export function unused() { return "removed from the bundle"; }

// app.js
import { used } from "./utils.js";
console.log(used());

To help the bundler, prefer libraries that publish ES modules, import named functions rather than whole namespaces, and mark your own package as side-effect free with "sideEffects": false in package.json when it is true.

Code splitting

Instead of one big file, split the code into chunks and load each only when needed. The usual split points are:

  1. Routes. Each page loads its own chunk.
  2. Heavy features. A chart, a map or an editor loads when the user opens it.
  3. Rarely used components. A modal or a settings panel.
flowchart TB
  Main["main.js (shared, small)"] --> Home["home chunk"]
  Main --> Dash["dashboard chunk"]
  Dash --> Chart["chart library chunk<br/>(loaded on demand)"]

Only the code for the current route is downloaded first.

The tool for this is dynamic import(). Bundlers see it and create a separate file automatically:

JavaScript
button.addEventListener("click", async () => {
  const { renderChart } = await import("./chart.js");
  renderChart(data);
});

A lazy loader with caching

The browser caches a module after the first import(), but it is still useful to share one promise so concurrent callers do not repeat work. Here the "module" is created in memory to keep the demo self-contained:

JS Lazy loading once

Press Run (or Ctrl + Enter) to see the console output here.

No output.

You can also prefetch a chunk when the browser is idle or the user hovers a link, so the click feels instant:

HTML
<link rel="prefetch" href="/js/dashboard.chunk.js" as="script">

Differential serving and modern targets

If your audience uses current browsers, target modern JavaScript. Transpiling async/await, classes and optional chaining down to old syntax makes code larger and slower. Set your build target (or the browserslist file) to the oldest browsers you truly support and remove polyfills you no longer need.

A practical routine

  1. Run the analyzer and write down the five biggest items.
  2. Remove, replace or lazy load each one.
  3. Re-measure transfer size, uncompressed size and Total Blocking Time.
  4. Add a size limit to your build so it cannot silently grow back (see Performance Budgets).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is 300 KB of JavaScript usually worse than a 300 KB image?

    Images decode off the main thread, while scripts consume main-thread CPU time after download.
  2. 2. Tree shaking works best with which module format?

    ES module imports and exports are static, so a bundler can see exactly which exports are unused.
  3. 3. Which is a good candidate for code splitting?

    Heavy code used by few visitors should be loaded on demand.
  4. 4. How do bundlers create a separate chunk from your code?

    A dynamic import() call tells the bundler that the module can be loaded later as its own file.

Summary

  • JavaScript costs transfer time and main-thread time; reduce both.
  • Minify and compress (Brotli or gzip) every text asset.
  • Use ES modules and named imports so tree shaking can remove dead code.
  • Split by route and by heavy feature using dynamic import().
  • Analyze the bundle regularly and guard it with a size budget.

Next: Debounce, Throttle and Idle Work