What Is Code Splitting? Loading JavaScript On Demand
Code splitting breaks one large bundle into multiple chunks so the browser downloads only the code needed for the current view.
Shipping your entire app as a single JavaScript file means users wait for code they may never run. Code splitting divides the bundle into chunks that load when needed, such as when a route is visited. It is one of the most effective ways to improve initial load time, and the bundler does the heavy lifting at build time.
How splitting happens
A dynamic import() tells the bundler to create a separate chunk that loads at runtime instead of up front. Route-based splitting is the most common pattern: each page becomes its own chunk fetched when the user navigates to it.
Shared chunks
Bundlers detect code shared across multiple entry points and factor it into common chunks so it is not duplicated. A vendor chunk for third-party libraries is a typical result, kept stable so its cache survives across deploys.
The benefits
- Faster initial page load from a smaller first download.
- Code for rarely visited pages is never fetched unless needed.
- Stable shared chunks stay cached across releases.
The trade-offs
Too many tiny chunks add request overhead and can hurt performance. Splitting also makes prefetching and loading states something you must design for, since a chunk can arrive after the user clicks.
Code splitting in CI/CD
Splitting changes how many output files the build produces and how they are hashed. Each chunk gets a content hash so the CDN can cache it forever and only changed chunks are re-downloaded after a deploy. The pipeline uploads the whole chunked output as one artifact.
Key takeaways
- Code splitting loads code on demand via dynamic imports, often per route.
- Shared and vendor chunks avoid duplication and stay cached across deploys.
- Each chunk is content-hashed so a deploy only invalidates what changed.