Code Splitting and Lazy Loading
What you'll learn: How modern bundlers let you split large JavaScript applications into smaller chunks that load only when needed, dramatically improving initial page load times.
The Problem with One Giant Bundle
When you bundle an entire application into a single JavaScript file, users must download and parse everything before your app becomes interactive—even code for features they might never use. Imagine serving a 500KB bundle when the user only needs 50KB to see the homepage.
What Code Splitting Does
Code splitting breaks your application into multiple smaller bundles (chunks). Instead of one massive file, you might have:
- A main bundle with critical startup code
- Separate chunks for different routes or features
- Vendor chunks for third-party libraries
Lazy loading means these chunks only download when actually needed—like when a user navigates to a specific page or clicks a button to open a feature.
How It Works in Practice
Bundlers like Webpack, Rollup, and Vite recognize dynamic import() as split points. When they encounter:
button.addEventListener('click', async () => {
const module = await import('./heavy-feature.js');
module.initializeFeature();
});
...they automatically create a separate chunk for heavy-feature.js that only downloads when the button is clicked.
The Performance Win
Think of it like a restaurant menu: instead of printing every possible dish description on one massive poster, you give customers a simple menu and bring detailed recipe cards only when they order specific items. The initial experience is faster, and bandwidth is used efficiently.
Route-based splitting is especially powerful—users visiting /about don't need the code for /dashboard.
Key Takeaway: Code splitting with lazy loading transforms monolithic bundles into on-demand chunks, reducing initial load time and improving performance by loading code only when users actually need it.