Why Use Lazy Loading In Angular

What is lazy loading?

Lazy loading is a routing technique in which the JavaScript components load in the browser only when their corresponding route is activated. The main aim of lazy loading is to improve the performance of the Angular app by restricting the unnecessary loading of components. Let us understand this with an example.

We have created an Angular app without lazy loading. Let us assume that the app has a login and a dashboard screen. Here, the login screen is the starting screen of the app. Whenever we load our app in the browser, both the screen scripts load in the memory of the browser, which eventually, reduces the performance of the app. Because we have a very small app with only two screens, it will not affect our app. But,  consider a project that consists of hundreds of components. In that case, it will reduce the performance of the app.

If we manage the same example with lazy loading, then the JavaScript of login screen will be loaded at the start of the application and the JavaScript of the dashboard will only be loaded when the routes match for the dashboard.

 

Implementing lazy loading

 

Note

I am using Angular 7 for this article.

Prerequisites

  1. Fundamental knowledge of TypeScript, HTML, Angular.
  2. Make sure the Angular CLI is installed in the machine.

Before getting started, you should know Angular Routing and Angular CLI commands. If you don’t have knowledge of Angular routing, then you can go through my Angular Routing Tutorial.

Let’s create an app with the name LazyLoadingExample. This app contains a header module for navigation, a dashboard component for the initial route, and two lazy modules named customer and supplier respectively. Both lazy modules contain a View component in them.

Step 1 - Create a new app with Routing

> ng new LazyLoadingExample --routing

Step 2 - Creating modules and components

> ng g c component/dashboard --spec false --module=app
> ng g m header/header --flat --module=app
> ng g c header/menu --spec false --module=header

> ng g m customer/customer --flat --routing
> ng g m supplier/supplier --flat --routing
> ng g c customer/view-customer --spec false --module=customer
> ng g c supplier/view-supplier --spec false --module=supplier

After generating the modules and components, our directories look like this.

Angular Lazy Loading

Code for app component.html.

  1. <app-menu></app-menu>  
  2. <router-outlet></router-outlet> 

Note
The code or snippet of designing is not included as our main focus is understanding lazy loading but you can download the source code from the attachment with this article.

Note
Make sure you have exported menu component from the header module so we can use it in the app component.

Step 3 - Configure routes for lazy modules

Code for customer-routing.module.ts

  1. import { NgModule } from '@angular/core';  
  2. import { CommonModule } from '@angular/common';  
  3. import { Routes, RouterModule } from '@angular/router';  
  4. import { ViewCustomerComponent } from'./view-customer/view-customer.component';  
  5. const routes: Routes = [  
  6.  { path:'view', component:ViewCustomerComponent } ];  
  7. @NgModule({  
  8.  declarations: [],  
  9.  imports: [CommonModule, RouterModule.forChild(routes)],  
  10.  exports:[RouterModule]  
  11. })  
  12. export class CustomerRoutingModule { } 

Code for supplier-routing.module.ts

  1. import { NgModule } from '@angular/core';  
  2. import { CommonModule } from '@angular/common';  
  3. import { Routes, RouterModule } from '@angular/router';  
  4. import { ViewSupplierComponent } from './view-supplier/view-supplier.component';  
  5. const routes: Routes = [  
  6. { path: 'view', component: ViewSupplierComponent } ];  
  7. @NgModule({  
  8.  declarations: [],  
  9.  imports: [ CommonModule, RouterModule.forChild(routes)],  
  10.  exports:[RouterModule]})  
  11. export class SupplierRoutingModule { } 

Step 4 - Configure lazy routes for app

In this step, point the lazy route to the lazy module from the app router. We can do this with the loadChildren property with the path to the module file. Then, reference the module with a hash #. This tells Angular to only load LazyModule when the lazy URL is activated.

Code for app-routing.module.ts

  1. import { NgModule } from '@angular/core';  
  2. import { Routes, RouterModule } from '@angular/router';  
  3. import { DashboardComponent } from './component/dashboard/dashboard.component';  
  4. const routes: Routes = [  
  5.  { path:'', component:DashboardComponent },  
  6.  { path:'customer', loadChildren:'./customer/customer.module#CustomerModule'},  
  7.  { path:'supplier', loadChildren:'./supplier/supplier.module#SupplierModule'}];  
  8. @NgModule({  
  9.  imports: [RouterModule.forRoot(routes)],  
  10.  exports: [RouterModule]  
  11. })  
  12. export class AppRoutingModule { } 

Step 5 - Add the navigation directive to the menu component.

Code for menu.component.html

  1. <div class="dropdown-menu" aria-labelledby="customerDropdown">  
  2.          <a class="dropdown-item" routerLink="customer/view">View Customer</a>  
  3.   </div>  
  4.   
  5. <div class="dropdown-menu" aria-labelledby="supplierDropdown">  
  6.          <a class="dropdown-item" routerLink="supplier/view">View Supplier</a>  
  7.   </div>  

Step 6- Verify Lazy Loading is Working.

Let’s make sure that Lazy Loading is working. In Chrome, open developer tools and click the "Network" tab. When you navigate to the lazy URL ‘customer/view’, you should see a customer-customer-module.js file rendered. In this demo, you can see it took 347ms and supplier-supplier-module.js loaded after you navigated to the lazy URL ‘supplier/view’.

 

Comparing application load time with or without Lazy Loading

I have created the above same application without lazy loading, so we can easily compare the load time of the application with or without lazy loading. Let us compare.

  1. Without Lazy Loading

    Angular Lazy Loading

  2. With Lazy Loading

    Angular Lazy Loading

If you see the bottom of both the images, you will find the finish load time. In the case of without lazy loading, the finish time is 1.9 seconds and in the case of lazy loading, the finish time is 721 microseconds. It clearly shows that lazy loading improves the performance of the application.

Note
The source code has both the solutions with and without lazy loading.

Conclusion

It is recommended to use lazy loading if you have lots of routes and components. I think the above description of implementing lazy loading is clear. Let me know of any questions you might have.


Similar Articles