Code Splitting
Code splitting divides an application into separately loadable chunks so a browser need not download and execute all code at startup.
Download Markdown (.md)Soroush’s Product Wiki · https://wiki.soroush.uk/topic/code-splitting/
01What it means
Code splitting creates multiple JavaScript or CSS outputs around entry points, routes, components, or dynamic imports. The browser loads an initial set and retrieves other chunks when navigation or interaction requires them. It changes delivery boundaries; it does not by itself remove unused code or guarantee smaller total transfer.[1][2]
- Application entrySmall initial code required for the first useful view
- Shared chunkStable dependencies reused across routes
- Route chunkCode fetched for a navigated destination
- Feature chunkDynamic import triggered by an interaction
- Loading + recoveryReserved state, errors, retry, and monitoring
Browser cache can reuse stable chunks across later navigation
Splitting changes when code is delivered; it neither removes unused code automatically nor guarantees less total transfer.
02Why it matters
Reducing initial code can shorten download, parsing, and execution on constrained devices. Poor boundaries, however, create request waterfalls, duplicate dependencies, and delays at the moment a user needs a feature.
03When to use it
Use code splitting when measured bundles contain substantial code that many users do not need initially. Split around meaningful product paths, then preload or prefetch only likely next work rather than maximizing the number of chunks.
04How it works
- Measure initial bundles and identify code not required for the first useful view.
- Choose stable route, feature, or component boundaries for separate chunks.
- Configure dynamic imports or build entry points and shared dependency handling.
- Load chunks on demand with explicit loading, error, and retry states.
- Monitor initial cost, cache reuse, request waterfalls, and interaction delay after deployment.
05A practical example
A commerce site moves its rarely used 3D product viewer into a separate chunk. Product pages become interactive sooner, and the viewer chunk starts only when a user opens the feature, with a retry state for network failure.
06Where it breaks
Splitting adds build and runtime coordination, chunk requests can fail, and too many small files increase overhead. Users who need every feature may download the same total code plus loader metadata.
Common mistakes
- Creating tiny chunks without accounting for request and coordination overhead.
- Splitting critical interaction code that users need immediately.
- Ignoring duplicate libraries across chunks and cache invalidation behavior.
- Reporting smaller files without measuring execution and user-visible timing.