Lazy loading in Angular lets you load modules asynchronously, speeding up application startup.
Angular developers utilise lazy loading when they only need to load the routes whose UI is being displayed. For example, if the user is on the homepage, no other site page should be loaded.
Benefits of Angular Lazy Loading
- Less Data Usage: Lazy loading divides application data into chunks that can be loaded when needed.
- Faster load time: JavaScript gives developers instructions to show and load webpage data. Angular has a render-blocking resource that delays JavaScript loading and renders the page.
- Lazy loading lets you chunk and load JavaScript. The web browser loads only the necessary portions, saving CPU and memory to draw and interpret the code.
Setp by step to setup lazyloading
Create an angular module and separate routing file to handle lazy loading module components.
ng g m product
Create Component Add a component to the products module next.
ng c goods
Add Navigation Link The developer must now add a lazy-loading header link. When the interrelated route is clicked, only the ‘products’ component loads.
//Example of Lazy Loading products page
<button type="button" routerLink="/home" [routerLinkActive]="['active']"> Home </button><button type="button" routerLink="/categories" [routerLinkActive]="['active']"> Categories </button>
<button type="button" routerLink="/products" [routerLinkActive]="['active']"> Products </button>
Implement Lazy Loading with loadChildren()
Lazy Load with loadUse loadChildren() to implement lazy loading in Children(). The ‘/products’ route component will be lazily loaded using Promise and Async.
- Using promise Implement lazy loading using loadChildren using promise-based syntax in app-routing.module.ts. const routes:
Const routes: Routes = [
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
},
{
path: 'products',
loadChildren: () =>
import('./products/products.module').then(m => m.ProductsModule)
}
];Here, ‘/products’ is the path property value. Additionally, the loadChildren parameter must include the promise-based system routes that are slowly loaded in the above code.
- Using async Instead of promises, async can implement lazy loading. Developers can simplify, show, and read code with const routes.
const routes: Routes = [
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
},
{
path: 'home',
loadChildren: () => import('./home/home.module').then(m => m.HomeModule)
},
{
path: 'categories',
loadChildren: () => import('./categories/categories.module').then(m => m.CategoriesModule)
},
{
path: 'products',
loadChildren: () => import('./products/products.module').then(m => m.ProductsModule)
}
];