What is Lazy Loading?
Lazy loading is a design pattern that delays the initialization of a resource until it is actually needed. In Angular, this means that the JavaScript for a specific feature (like an Admin Dashboard or a Code Editor) isn't downloaded until the user navigates to that feature's route. This significantly reduces the Initial Bundle Size and improves the Time to Interactive (TTI).
- Why Use Lazy Loading?
In large-scale applications, the 'Main' bundle can become bloated. As an Architect, you should aim for a lean initial load. Lazy loading ensures that a user only downloading the core framework and the landing page doesn't have to wait for the code of the entire 'Settings' or 'Analytics' module.
- Faster Initial Load: Users see the first page quicker.
- Reduced Bandwidth: Only necessary code is transferred.
- Better Resource Management: The browser doesn't have to parse unused JavaScript.
- Implementing Route-Based Lazy Loading
In modern Angular (v15+), you can lazy load individual standalone components using the loadComponent property in your route configuration. For older module-based apps, you use loadChildren.
Lazy Loading vs. Eager Loading
Eager loading is the default behavior where all components are imported at the top of the file and bundled into the main package.
| Feature | Eager Loading | Lazy Loading |
|---|---|---|
| Initial Load | Slow (Large bundle) | Fast (Small main bundle) |
| User Experience | Wait at start | Small wait during navigation |
| Implementation | Standard 'import' at top | Dynamic 'import()' in routes |
| Best For | Small apps / Critical paths | Large Feature modules / Admin panels |
- Preloading Strategies
To avoid a 'loading' delay when a user clicks a link, you can use a Preloading Strategy. This tells Angular to download the lazy-loaded modules in the background after the initial app has loaded and the user is idle.