Why Lazy Loading?
Benefits of lazy loading:- Smaller Initial Bundle: Load only what’s needed for the initial view
- Faster Startup: Reduce application bootstrap time
- Better Performance: Load features only when users need them
- Efficient Resources: Minimize memory usage by loading code on-demand
Lazy loading is implemented using dynamic imports (
import()) and the loadChildren or loadComponent properties in route configurations. The implementation can be found in packages/router/src/router_config_loader.ts.Lazy Loading Routes
Using loadChildren (Recommended)
The modern approach usesloadChildren with dynamic imports:
app.routes.ts
products/products.routes.ts
Default Exports
You can also use default exports:products/products.routes.ts
app.routes.ts
Lazy Loading Components
Standalone Components
Lazy load individual components withloadComponent:
app.routes.ts
about/about.component.ts
The
loadComponent property is defined in packages/router/src/models.ts:626 and supports lazy loading standalone components.Lazy Loading NgModules (Legacy)
For applications still using NgModules:app-routing.module.ts
products/products.module.ts
Guards with Lazy Loading
Using canMatch for Lazy Routes
canMatch guards prevent lazy-loaded modules from loading:
feature-flag.guard.ts
routes.ts
Using canActivate
canActivate guards run after the module loads:
auth.guard.ts
routes.ts
Use
canMatch when you want to prevent loading. Use canActivate when the module should load but activation depends on a condition.Preloading Strategies
Preloading loads lazy routes in the background after initial load:PreloadAllModules
Preload all lazy routes automatically:main.ts
NoPreloading (Default)
Disable preloading (load only on-demand):main.ts
Custom Preloading Strategy
Create a custom strategy for selective preloading:custom-preload.strategy.ts
routes.ts
main.ts
Network-Aware Preloading
Preload based on network conditions:network-aware-preload.strategy.ts
Lazy Loading with Providers
Provide services scoped to lazy-loaded routes:products/products.routes.ts
Performance Monitoring
Monitor lazy loading performance:app.component.ts
Real-World Example
Comprehensive lazy loading setup:app.routes.ts
main.ts
Bundle Analysis
Analyze your lazy-loaded bundles:Best Practices
Group by Feature
Organize lazy-loaded modules by feature or functionality for better maintainability.
Use Smart Preloading
Implement custom preloading strategies based on user behavior and network conditions.
Monitor Bundle Sizes
Regularly analyze bundle sizes to identify optimization opportunities.
Prefer canMatch for Lazy Routes
Use
canMatch guards to prevent unnecessary module downloads.Common Patterns
Feature Shell Pattern
Create a shell component for lazy-loaded features:products/products.routes.ts
Conditional Lazy Loading
Load different modules based on conditions:routes.ts
Next Steps
Route Guards
Learn how to protect your lazy-loaded routes with guards
Defining Routes
Master route configuration and parameters
