Skip to content
Velloreth
Web Development 5 min read

Code Splitting: Shipping Less JavaScript

Split a bundle so a page loads only the code it needs. Learn the route split, the dynamic import, and how to measure the result.

By

Why split

A single bundle ships code the page does not use. A user who visits the home page downloads the code for the settings page, the admin panel and the chart library.

The cost: a larger download, a longer parse, and a later time to interactive.

The fix: split the bundle so a page loads only what it needs.

The route split

The most effective split. Each route loads its own code.

const routes = [
  { path: '/', component: () => import('./pages/Home.js') },
  { path: '/settings', component: () => import('./pages/Settings.js') },
];

The home page does not download the settings code.

The framework support: most routers have a lazy option, and a meta-framework such as Next.js or Astro splits by route by default.

The result: the initial bundle contains the shell and the current route.

The dynamic import

A dynamic import creates a split point at the call site.

button.addEventListener('click', async () => {
  const { openModal } = await import('./modal.js');
  openModal();
});

The module is loaded when the click happens, not on the initial load.

The use cases:

  • A modal or a dialog
  • A chart library
  • A rich text editor
  • A heavy form
  • A feature behind a flag

The trade-off: the first interaction waits for the download. A prefetch can hide it.

// Prefetch when the user hovers
button.addEventListener('mouseenter', () => {
  import('./modal.js');
});

The vendor chunk

Separate the dependencies from the application code.

// vite.config.js
export default {
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['react', 'react-dom'],
        },
      },
    },
  },
};

Why: the dependencies change less often than the application, so a browser caches the vendor chunk across a deploy. A user who returns after a release downloads only the application chunk.

The caution: too many chunks means too many requests. A vendor chunk and a route chunk per page is usually enough.

The component split

A component that is not needed on the initial render is a candidate.

const Chart = lazy(() => import('./Chart'));

<Suspense fallback={<Spinner />}>
  <Chart data={data} />
</Suspense>

A Suspense boundary shows a fallback while the module loads.

The caution: a split for a small component adds a request and a loading state for little gain. Split a component that is large or that pulls in a large dependency.

Measuring

Measure before and after, or the split is a guess.

The bundle analysis:

npx vite-bundle-visualizer
# or
npx source-map-explorer dist/assets/*.js

The metrics:

MetricWhat it shows
Initial JS transferredthe download cost
Time to interactivewhen the page responds
Largest contentful paintwhen the main content is visible
Total blocking timethe main-thread cost

The target: a smaller initial bundle and a better time to interactive. A split that adds a request without a metric change did not help.

The Lighthouse audit reports the unused JavaScript, which is the code that a split could remove.

The pitfalls

Too many chunks. Each is a request, and a request for a 2 KB module costs more than it saves.

A waterfall. A chunk that loads another chunk that loads another. The requests are serial, so the total is the sum.

A split that breaks the cache. A chunk name that changes on every build invalidates the cache. Use a content hash.

A loading state for a fast module. A spinner that appears for 20 milliseconds is a flicker.

A split that hides a dependency. A module that is imported dynamically and also statically is in both chunks.

A preload for everything. A preload for a chunk that is not needed competes with the critical resources.

The framework defaults

Next.js splits by route and supports dynamic() for a component.

Astro ships zero JavaScript by default and hydrates only the interactive islands.

Vite splits a dynamic import automatically.

Webpack splits a dynamic import and supports splitChunks for the vendor.

The default is often good. Measure before adding a manual split.

The build output

A split is only visible in the build output, so reading it is the first step of any optimisation. The output lists each chunk with its size, and the entry chunk is the one that loads on every page. A chunk that is larger than expected usually contains a dependency that was pulled in by a single import, and the bundle analyser shows which one. The second thing to read is the number of chunks: a build with forty small chunks has a request problem, and a build with one large chunk has a download problem. The third is the hash: a chunk name with a content hash changes only when the content changes, which is what makes the browser cache work across a deploy. Reading the output before and after a change is the only way to know whether the change helped.

Common mistakes

Splitting everything. Too many requests.

No measurement. The split is a guess.

A chunk name without a hash. The cache is invalidated on every build.

A dynamic import for a module needed on the first render. The page waits for a request it could have avoided.

A waterfall of chunks. The requests are serial.

A preload for a non-critical chunk. It competes with the critical path.

Ignoring the parse cost. A large chunk costs parse time as well as download time.

A split that duplicates a dependency. The same library is in two chunks.

A quotable summary

Code splitting divides a bundle so a page loads only the code it needs, and the most effective split is by route. A dynamic import creates a split point at the call site, and a vendor chunk separates the stable dependencies from the application code so the browser can cache them across a deploy. Split at a route, a large feature, or a component that is not needed on the initial render, and measure the initial bundle and the load metrics before and after, because a split without a measurement is a guess.

For the related topics, see javascript-performance-tips and javascript-modules-guide. For the broader context, css-container-queries-in-practice and javascript-debugging-console.

Frequently asked questions

What is code splitting?
It is the practice of dividing a JavaScript bundle into several files that are loaded on demand. A page loads only the code it needs, so the initial download is smaller and the page becomes interactive sooner. The split points are usually a route, a component, or a feature.
What is a dynamic import?
It is an import that returns a promise and loads the module at runtime. It creates a split point, so the bundler emits a separate file. It is written as import('./module') rather than a static import at the top of the file.
What is the difference between code splitting and tree shaking?
Tree shaking removes the unused exports from a module at build time. Code splitting divides the remaining code into several files that load on demand. They are complementary: tree shaking reduces what is in a chunk, and code splitting decides which chunk loads when.
Should I split every component?
No. Each split point is a network request, and a request for a tiny module costs more than it saves. Split at a route, at a large feature, and at a component that is not needed on the initial render, such as a modal or a chart library.
How do I know if code splitting helped?
Measure the bundle size and the load metrics before and after. Look at the initial JavaScript transferred, the time to interactive, and the largest contentful paint. A split that reduces the initial bundle and improves the metrics helped; a split that adds a request without a metric change did not.
What is a vendor chunk?
It is a chunk that contains the third-party dependencies rather than the application code. It changes less often than the application, so a browser can cache it across a deploy. It is a common split because the dependencies are large and stable.