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, admin panels.
- Large libraries used in one place: date libraries, PDF renderers, syntax highlighters.
Do not split tiny components: each chunk adds a network request and a loading state.
4. Avoiding loading spinners: prefetch
- Start the import on hover or focus of a link, before the click.
- Use
<link rel="prefetch">for chunks likely needed on the next navigation (low priority) and<link rel="preload">for resources needed on the current page (high priority). - Prefetch during idle time with
requestIdleCallback.
5. Lazy loading other assets
- Images and iframes:
loading="lazy"defers off-screen ones. Do not lazy-load the LCP hero image. - Below-the-fold sections: render on visibility with
IntersectionObserver.
6. Measuring
Use a bundle analyzer to find large dependencies, and watch Core Web Vitals: less JavaScript on first load usually improves INP and LCP. Tree shaking removes unused exports from ES modules, but it does not split code; both techniques work together.
Code Splitting Interview Summary
Split by route first, then by heavy features; load chunks with import()/React.lazy behind Suspense; prefetch likely next chunks; never lazy-load what is needed for the first paint.
