Code splitting divides your JavaScript into smaller bundles that load only when needed. This reduces the initial download size and speeds up page loads.
Types of code splitting
Route-based splitting
Load code for each page separately:
const Home = lazy(() => import('./Home'));
const About = lazy(() => import('./About'));
Component-based splitting
Load components when they're needed:
const Chart = lazy(() => import('./Chart'));
Library splitting
Separate vendor code from application code.
Benefits of code splitting
- Smaller initial bundle size
- Faster initial page load
- Better caching (unchanged chunks stay cached)
- Load only what's needed
Implementing code splitting
React
import { lazy, Suspense } from 'react';
const Component = lazy(() => import('./Component'));
<Suspense fallback={<Loading />}>
<Component />
</Suspense>
Dynamic imports
button.onclick = async () => {
const module = await import('./heavy-module.js');
module.doSomething();
};
Code splitting impact
Effective code splitting can:
- Reduce initial JS by 50%+
- Improve LCP and TTI
- Lower TBT
Related Terms
JavaScript Execution Time
The time the browser spends parsing, compiling, and executing JavaScript code, which can block the main thread and delay interactivity.
Lazy Loading
A design pattern that defers the loading of non-critical resources until they are needed, typically when they enter the viewport.
Minification
The process of removing unnecessary characters from code without changing its functionality, reducing file size for faster downloads.
Render Blocking
Resources that prevent the browser from rendering page content until they are fully downloaded and processed.