Performance & Security

Code Splitting

Code splitting breaks your JavaScript bundle into smaller chunks that load on demand. Users get a fast initial load and only download the code they actually use — critical for improving Core Web Vitals and mobile performance.

What is code splitting in JavaScript?

Code splitting breaks your JavaScript bundle into smaller chunks that load only when needed, so the first page load downloads less. Use dynamic import() to load a module on demand, for example a chart library only when the chart opens. Frameworks split by route automatically, and React's lazy() splits components.

button.addEventListener("click", async () => {
  const { renderChart } = await import("./chart.js");   // separate chunk
  renderChart(data);
});

// React
const Editor = lazy(() => import("./Editor"));
<Suspense fallback={<Spinner />}><Editor /></Suspense>

Splitting Strategies

Route-based

Highest impact

Each page/route gets its own chunk. Users only download code for pages they visit. Automatic in Next.js App Router, easy in React Router with lazy().

Home → bundle-home.js (12KB)
Dashboard → bundle-dashboard.js (45KB)

Vendor

High impact

Separate rarely-changing npm packages from your app code. Enables long-term browser caching — library chunk stays cached even when your app code changes.

vendor.js (150KB) — cached forever
app.js (25KB) — re-downloaded each deploy

Feature-based

Medium impact

Admin panel, PDF export, chart library — only load for users who actually use that feature. Zero cost for everyone else.

isAdmin && import('./admin-panel')
format==='pdf' && import('./pdf-lib')

Interaction-based

Medium impact

Load module on hover/first click (not immediately on page load). Great for modals, tooltips, editors that are rarely opened.

btn.addEventListener('mouseenter', () =>
  import('./chart-editor'), { once: true })

Common Pitfalls

Over-splitting: too many tiny chunks — HTTP overhead exceeds savings (especially with HTTP/1.1)
Aim for chunks >20KB. HTTP/2 multiplexing helps, but don't split below ~20KB. Profile before optimizing.
Dynamic importing inside a loop — creates N separate chunks for N items instead of one
Import outside loops, or use a shared chunk name. import('./item-' + id) creates unpredictable chunks.
Not handling loading/error states for React.lazy() — blank screen if chunk fails to load
Always wrap lazy() in Suspense with a fallback, and add an ErrorBoundary to catch network failures.
Forgetting to analyze the bundle — splitting blindly may not help the real bottleneck
Run webpack-bundle-analyzer or vite-bundle-visualizer first. Fix the biggest chunks, not the smallest ones.

Interactive Demo

Code Editor

<button id="load">Load the chart module</button>
<div id="chart"></div>

Preview

Code Splitting — step by step

1 / 4
1

The Problem: Monolithic Bundles

Shipping one giant JS bundle means users download code for every route and feature up front — even parts they will never visit. Code splitting defers loading of modules until they are actually needed.

1 of 4
💡Split at Route and Vendor Boundaries
Separate your vendor dependencies (React, lodash) into their own chunk. Vendor code changes less often than your app code, so users keep it cached across deployments while only re-downloading your changed app chunk.

🎯 Quick Check

What does dynamic import() return in JavaScript?

Code Splitting: summary

Key points

  • Split heavy, rarely used features: editors, charts, maps, admin screens.
  • Prefetch chunks the user is likely to need next.
  • Analyse bundles with vite-bundle-visualizer or @next/bundle-analyzer.

Frequently asked questions

›Does code splitting improve SEO?

Indirectly. Less JavaScript on first load improves Core Web Vitals, which are a ranking factor.