What is Code Splitting?
Code splitting breaks your JavaScript bundle into smaller chunks that load on demand, so users download only the code needed for the current page or feature instead of the whole app up front.
Why it matters
Large bundles hurt every Core Web Vital: more bytes to download, parse and compile delays interactivity (INP) and the main content (LCP), especially on mobile devices and slow networks.
How it works
Bundlers (webpack, Vite/Rollup, Turbopack, esbuild) create a separate chunk wherever they see a dynamic import(). At runtime, calling import("./module.js") fetches that chunk the first time and returns a promise of the module.
Common split points
- Routes: each page in its own chunk. Next.js, Remix and SvelteKit do this automatically.
- Heavy components shown later or rarely: charts, rich-text editors, maps, video players, admin panels.
- Interaction-triggered features: load the emoji picker when the button is clicked.
- Large libraries used in one place: PDF generation, date or markdown libraries.
- Vendor chunks: dependencies that change rarely, cached separately from app code.
In React and Next.js
React.lazy(() => import("./Chart"))with<Suspense fallback={...}>.next/dynamicfor client components, withssr: falsefor browser-only libraries.- React Server Components keep server-only code out of the client bundle entirely.
Trade-offs
Too many tiny chunks add request overhead and loading waterfalls. Split where it saves meaningful bytes, preload chunks you know will be needed soon (on hover, on idle), and measure with bundle analysers.
Code example
1// Route- or feature-level split: this chunk is downloaded only when needed2async function openReportEditor() {3 const { createEditor } = await import("./report-editor.js"); // separate chunk4 return createEditor(document.querySelector("#editor"));5}67// React: lazy component + Suspense8import { lazy, Suspense, useState } from "react";9const Chart = lazy(() => import("./HeavyChart")); // its own chunk1011export function Dashboard() {12 const [showChart, setShowChart] = useState(false);13 return (14 <>15 {/* preload on hover so the click feels instant */}16 <button onMouseEnter={() => import("./HeavyChart")} onClick={() => setShowChart(true)}>17 Show chart18 </button>19 {showChart && (20 <Suspense fallback={<p>Loading chart...</p>}>21 <Chart />22 </Suspense>23 )}24 </>25 );26}2728// Next.js: client-only library without SSR29import dynamic from "next/dynamic";30export const Map = dynamic(() => import("./LeafletMap"), { ssr: false, loading: () => <p>Loading map...</p> });
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.