Lazy loading in routing is a technique where certain parts of an application—typically routes or modules—are loaded only when they are needed, instead of at the initial load. This helps reduce the initial bundle size and improves the performance, especially load time of web applications.
🚀 What Is Lazy Loading?
Instead of loading the entire application upfront, lazy loading delays the loading of route-specific code until a user navigates to that route. This is commonly used in single-page applications (SPAs) built with frameworks like React, Angular, or Vue.
🔍 Why Is Lazy Loading Important?
-
Faster Initial Load:
Only the essential code is loaded first. This speeds up the initial page load, improving user experience and Core Web Vitals (like First Contentful Paint). -
Reduced Bandwidth Usage:
Users only download what's necessary for the routes they visit, which is more efficient—especially on mobile or slow networks. -
Better Scalability:
As your app grows, lazy loading helps keep the main bundle small and manageable. -
Improved Perceived Performance:
Because the main UI loads quickly, users feel the app is faster and more responsive.
✅ Example in React (React Router v6)
Here, Dashboard
and Settings
components are only loaded when the user visits /dashboard
or /settings
.
✅ Example in Angular
Angular uses loadChildren
to lazily load modules. The DashboardModule
is only fetched when the /dashboard
route is accessed.
⚖️ Lazy Loading vs. Eager Loading
Feature | Lazy Loading | Eager Loading |
---|---|---|
Load Timing | On demand (when route is visited) | At initial load |
Performance Impact | Faster initial load, better scalability | Slower initial load as all code is loaded |
Ideal For | Large or modular apps | Small or simple apps |
🧠 Summary
Lazy loading in routing is a critical performance optimization technique. It minimizes the initial payload and makes your application feel faster by loading only the necessary code when needed. It's especially beneficial in large, modular applications or SPAs with many routes and components.