Code Splitting and Lazy Loading
Split large JavaScript bundles into on-demand chunks with dynamic imports and route-based splitting so users download only the code they actually need.
The Monolithic Bundle Problem
Shipping all JavaScript in one bundle forces users to download code for pages they may never visit. Code splitting breaks the bundle into smaller chunks loaded only when needed.
Dynamic import()
The dynamic import() expression returns a promise and tells bundlers to create a separate chunk. The module loads on demand at runtime.
button.addEventListener('click', async () => {
const { renderChart } = await import('./chart.js');
renderChart();
});All lessons in this course
- Minimizing JavaScript Payload
- Efficient Script Loading Strategies
- Web Workers and Off-Main Thread
- Code Splitting and Lazy Loading