Code Splitting and Lazy Loading
JavaScript is the most expensive resource on the web byte-for-byte: it must be downloaded, parsed, compiled, and executed before the page becomes interactive. Code splitting breaks a single bundle into chunks so users download only what the current screen needs. Webpack’s code splitting guide and React’s lazy() reference cover the details.
1. Dynamic import
Static import statements are bundled together. A dynamic import() returns a promise and tells the bundler to create a separate chunk.
button.addEventListener('click', async () => {
const { openEditor } = await import('./editor'); // fetched on first click
openEditor();
});
2. React.lazy and Suspense
const SettingsPage = React.lazy(() => import('./SettingsPage'));
function App() {
return (
<Suspense fallback={<Spinner />}>
<Routes>
<Route path="/settings" element={<SettingsPage />} />
</Routes>
</Suspense>
);
}
React.lazy expects a module with a default export. While the chunk loads, the nearest Suspense boundary shows its fallback.
3. Where to split
- Routes: the highest-value split. Each page becomes its own chunk (frameworks like Next.js do this automatically).
- Heavy, rarely used components: rich text editors, charts, maps, modals,... premium content.
