liveBook · Manning

Code splitting

As explained in Secrets of the JavaScript Ninja, Third Edition

A build technique that divides application code into separate output chunks, often so they can be loaded independently.

Code splitting divides a site’s JavaScript into chunks, such as shared code and separate page chunks. Visitors can download less code initially and fetch smaller chunks as they navigate. section 13.3 section 13.3.1

For a site with ten pages, the main options have different tradeoffs:

  • One bundle keeps navigation fast, but makes visitors download all the site’s JavaScript before a page can render. section 13.3.1
  • A bundle per page reduces the initial download, but navigating can require downloading dependencies already included with the first page. section 13.3.1
  • A shared chunk plus page-specific chunks can limit both the initial download and later downloads. Multiple ESM chunks can add round trips; modulepreload links can start downloading needed chunks earlier. section 13.3.1

Splitting can also help browser caching: changes limited to one page’s chunk need not make visitors re-download shared code or affect other pages. Modern bundlers split code automatically using heuristics; better results may require experimenting with manual splitting and combining it with prefetching. Bundler-specific configuration is outside this treatment. section 13.3.1 section 13.3

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains chunking tradeoffs and preload options, but defers bundler-specific configuration.
Examples
Compares one bundle, per-page bundles, and shared-plus-page chunks across a ten-page site.
What you can do after
Apply code splitting through bundler configuration and combine manual chunking with prefetching to tune the site experience.
How it connects
Connects code splitting to bundlers, module graphs, ESM chunks, browser caching, and modulepreload.

Also explained in

Compare how 4 books explain code splitting →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.