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 impactEach 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 impactSeparate 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 impactAdmin 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 impactLoad 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
Interactive Demo
Code Editor
<button id="load">Load the chart module</button>
<div id="chart"></div>Preview
Code Splitting — step by step
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.
🎯 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-visualizeror@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.