Skip to main content
Saved

Pattern Performance Advanced

Code Splitting

You can split your bundle into chunks that load on demand, so the code for a route or feature only downloads when a user actually needs it.

Examples
React, Vue, Svelte and native web
Read
5 min

The problem

Your homepage might take 8 seconds to become interactive, because users have to download the entire admin dashboard, a rich text editor they’ll never use, three charting libraries, and every route they might visit someday, all before they can click a single button.

The pattern

With dynamic import() statements, you can split your code by route or by large feature. Your bundler then creates separate chunk files that load on demand, instead of putting everything into one bundle that users download up front.

Problem

I’ve seen production apps ship 2MB of JavaScript for landing pages that only needed 100KB, and mobile users on 3G were left looking at a blank screen for 15 seconds. Even users with fast connections have to wait, because the browser parses all that JavaScript whether it runs or not.

Most of this code is for features that users might never open, such as checkout flows for people who aren’t buying, or admin panels for people who aren’t admins.

Solution

Teams most often split at route boundaries, so the code for the settings page only downloads when a user goes to that page. You can also split at the component level for heavy dependencies like charting libraries, or by feature flag, so free-tier users don’t download the code for premium features.

You don’t have to configure these chunks yourself. If you write import('./Dashboard') instead of import './Dashboard', Webpack and Vite automatically create a separate chunk for that module and its dependencies, and that chunk only downloads when the code that calls import() runs.

People often use the terms code splitting, dynamic import(), and lazy loading as if they meant the same thing. The bundler does the code splitting, when it writes your code out as several chunk files. Dynamic import() is the syntax that tells the bundler where to split, and it fetches the chunk when it runs. With Lazy Loading, you choose when that fetch happens, such as on navigation, on a click, or when something scrolls into view.

Code that the first screen needs should stay in the main bundle, because splitting it out only adds another request before the page can render. A small app might not need splitting at all.

Example

Splitting by route is the most common approach, but splitting at the component level also works well for heavy widgets.

Route-Based Splitting

import { lazy, Suspense } from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';

const Dashboard = lazy(() => import('./pages/Dashboard'));
const Analytics = lazy(() => import('./pages/Analytics'));
const Settings = lazy(() => import('./pages/Settings'));

function App() {
  return (
    <BrowserRouter>
      <Suspense fallback={<LoadingSpinner />}>
        <Routes>
          <Route path="/dashboard" element={<Dashboard />} />
          <Route path="/analytics" element={<Analytics />} />
          <Route path="/settings" element={<Settings />} />
        </Routes>
      </Suspense>
    </BrowserRouter>
  );
}

Frameworks with file-based routing, such as SvelteKit and Next.js, already split each route into its own chunk, so you don’t have to write any route-splitting code.

Component-Level Splitting

You can split out heavy components, such as charts, separately from your routes. In both versions, the chart’s chunk only downloads once showChart is true:

import { lazy, Suspense } from 'react';

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

function Dashboard({ showChart, data }) {
  return (
    <div>
      <h1>Dashboard</h1>
      {showChart && (
        <Suspense fallback={<ChartSkeleton />}>
          <Chart data={data} />
        </Suspense>
      )}
    </div>
  );
}

Named Chunks and Prefetching (Webpack)

With Webpack’s magic comments, you can control what each chunk is called and how it loads. With webpackPrefetch, the browser downloads the chunk during idle time after the current page has loaded, which suits a page the user is likely to visit next. With webpackPreload, the browser downloads the chunk at the same time as the chunk that imports it, which suits code the current page needs almost immediately:

const Dashboard = () => import(
  /* webpackChunkName: "dashboard" */
  /* webpackPrefetch: true */
  './pages/Dashboard'
);

const HeavyEditor = () => import(
  /* webpackChunkName: "editor" */
  /* webpackPreload: true */
  './components/RichTextEditor'
);

Feature Flag Splitting

If you combine dynamic imports with feature flags, the app only loads the code for features that are enabled:

// Each import() path is a string literal, so the bundler can find it and create a chunk.
const features = {
  'advanced-analytics': () => import('./features/AdvancedAnalytics'),
  'admin-panel': () => import('./features/AdminPanel')
};

async function loadFeature(featureName) {
  // isEnabled() checks your feature flag service
  if (!isEnabled(featureName) || !features[featureName]) return null;

  const module = await features[featureName]();
  return module.default;
}

Vendor Splitting Configuration

If vendor libraries are in their own chunks, separate from your app code, browsers can keep them cached when only your own code changes:

// webpack.config.js
module.exports = {
  optimization: {
    splitChunks: {
      cacheGroups: {
        vendor: { test: /[\\/]node_modules[\\/]/, name: 'vendor', chunks: 'all' },
        common: { minChunks: 2, name: 'common', chunks: 'all' }
      }
    }
  }
};

// vite.config.js (Vite 8, which bundles with Rolldown)
export default {
  build: {
    rolldownOptions: {
      output: {
        codeSplitting: {
          groups: [
            { name: 'react-vendor', test: /[\\/]node_modules[\\/](react|react-dom|react-router-dom)[\\/]/ },
            { name: 'charts', test: /[\\/]node_modules[\\/](chart\.js|d3[^\\/]*)[\\/]/ }
          ]
        }
      }
    }
  }
};

Error Handling and Preloading

If a chunk fails to download, the component from lazy() throws the error during render, so an Error Boundary around the Suspense can show a fallback. The link starts downloading the chunk when the user hovers over it, and lazy() reuses that download after the click:

const Dashboard = lazy(() => import('./pages/Dashboard'));

function DashboardRoute() {
  return (
    <ErrorBoundary fallback={<ChunkLoadError />}>
      <Suspense fallback={<LoadingSpinner />}>
        <Dashboard />
      </Suspense>
    </ErrorBoundary>
  );
}

function DashboardLink() {
  return (
    <Link to="/dashboard" onMouseEnter={() => import('./pages/Dashboard')}>
      Dashboard
    </Link>
  );
}

Benefits

  • The initial bundle gets smaller, because users download only what they need for the current page.
  • Pages become usable sooner on all devices, because there’s less code to download and parse before users can interact with the page.
  • Mobile users on slow connections get a usable page faster, and with 100KB to download instead of 2MB, they’re more likely to stay instead of giving up.
  • Features that a user doesn’t open add nothing to their download, so admin panels stay out of regular users’ bundles, and premium features don’t slow the app down for free-tier users.
  • Vendor libraries are cached separately from app code, so when you deploy an update, users’ cached copies of React and other dependencies are still valid.
  • Less JavaScript up front helps loading metrics like FCP and LCP, and less script competing for the main thread helps INP. LCP and INP are both Core Web Vitals, which Google uses as a search ranking signal.

Tradeoffs

  • Navigation can feel slower at first, because users see a loading spinner while the chunk downloads the first time they visit each route.
  • Each split point needs a loading state, and without fallbacks, users might see blank screens and layout shifts while chunks load.
  • Your build configuration gets more complex, and it takes extra effort to debug code across chunks and to tune where you split.
  • On HTTP/1.1 connections, lots of small files can make the page load more slowly because each request has its own overhead, though HTTP/2 multiplexing mostly removes that problem.
  • Choosing a chunk size is tricky, because lots of tiny chunks add request overhead, and with only a few large ones, users end up downloading code they don’t need, just as they did before you split the bundle.
  • Dynamic imports return promises, so you need to handle failed network requests and show the user an error state.
  • If you prefetch too many chunks, you waste users’ bandwidth on pages they never visit, and if you prefetch too few, navigation can feel slow.
  • Unless you configure your bundler properly, shared dependencies can end up duplicated across chunks, which increases the total download size.

Summary

Code splitting breaks your bundle into chunks that load on demand, so the first page loads faster because users only download what they need. Route boundaries are the usual place to split, and heavy features can load when someone actually opens them. If you also preload the routes a user is likely to visit next, those chunks have often finished downloading by the time the user clicks, and the first page still loads quickly.

See also

Next in Performance Debounce Debouncing delays a function call until events have stopped for a short time, so a burst of rapid calls becomes a single call.

A monthly email
from Den Odell.

What I'm thinking about frontend patterns, plus news when the site changes.

No spam. Unsubscribe anytime.