Angular — Lazy Loading
What is Lazy Loading?
Loading modules/components only when needed, reducing initial bundle size.
Lazy Load Routes
const routes: Routes = [
{
path: 'admin',
loadChildren: () => import('./admin/admin.module')
.then(m => m.AdminModule)
},
{
path: 'shop',
loadComponent: () => import('./shop/shop.component')
.then(m => m.ShopComponent)
}
];
Preloading
@NgModule({
imports: [
RouterModule.forRoot(routes, {
preloadingStrategy: PreloadAllModules
})
]
})
Preloading Strategies
| Strategy | Description |
|---|---|
| NoPreloading | Default, no preloading |
| PreloadAllModules | Preload everything |
| Custom | Selective preloading |
Custom Preloading
export class CustomPreloading implements PreloadingStrategy {
preload(route: Route, fn: () => Observable<any>): Observable<any> {
if (route.data?.['preload']) {
return fn();
}
return of(null);
}
}
const routes: Routes = [
{
path: 'shop',
loadChildren: () => import('./shop/shop.module')
.then(m => m.ShopModule),
data: { preload: true }
}
];
Benefits
- Faster initial load
- Reduced bundle size
- Better performance
- On-demand loading
Mini Practice
- Lazy load a module
- Lazy load a component
- Add preloading
- Create custom preloading
Up Next
Continue with State Management — state management patterns.
Related Topics
Frequently Asked Questions about Lazy Loading
What is Lazy Loading in Angular?
Lazy Loading is a fundamental concept in Angular. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Lazy Loading?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Lazy Loading.
Why is Lazy Loading important in Angular?
Lazy Loading is essential for Angular development. Understanding this concept will help you write better code and solve real-world problems more effectively.