How to Implement Lazy Loading in Angular

Muhammad Adil Feb 02, 2024
  1. Usage of Lazy Loading in Angular
  2. Implement Lazy Loading in Angular
How to Implement Lazy Loading in Angular

This tutorial will discuss the usage of lazy loading in Angular and how to implement it.

Lazy loading is the process of loading a webpage’s resources in a delayed manner. This technique is typically used on web pages with large amounts of data or images, not at the top level.

Angular lazy loading helps load only the required resources for a given page. This reduces the initial download size and improves your application’s performance by reducing network requests.

It can be achieved using Angular’s built-in Lazy Load module or an external module such as Angular Universal Lazy Load Module, which relies on Webpack for configuration and builds.

Usage of Lazy Loading in Angular

The most common use case for lazy loading is when loading data from an API, but you don’t want to fetch all of the data. It will not work if your app has a single view without routing.

Lazy loading guarantees that just the essential modules are loaded and used when the application is first deployed. This benefits the application in terms of performance, as it reduces load times, resulting in a more responsive application for the end-user.

It takes some time to load all the modules, so what it does is it loads only a few modules when the user first visits a page and then loads more as needed.

Let’s discuss some of the Angular lazy loading use cases.

  • Deferring non-critical scripts and stylesheets until they are needed;
  • Vendor-facing and customer-facing screens on an e-commerce website might be separated into different modules. You can also construct a payment module on its own.
  • Loading scripts and stylesheets only on demand.

Implement Lazy Loading in Angular

Implementing lazy loading in Angular is a very straightforward process. We must add the correct modules and set up our routes.

The first step is to add the necessary modules for lazy loading. We do this by importing LazyModule from @angular/router and adding it to our imports array in our application module’s NgModule decorator.

Then, we must configure our routes to specify which modules should be loaded on-demand or lazily loaded on demand. We add a new route with loadChildren: 'lazy-loaded-child-routes' as an attribute or modify an existing route.

Example:

TypeScript code (app.component.ts):

import { Component, NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
@Component({
    selector: 'my-app',
    templateUrl: './app.component.html'
})
export class AppComponent { }
@Component({
    selector: 'app-home',
    template: '<h3>Home Active!!!</h3>',
})
export class AppadComponent  {}
const routes: Routes = [
    { path: 'Home', component: AppadComponent },
    { path: 'About', loadChildren: './lazy-loading.module#SecondModule' }
];
@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class RootRoutingModule { }

TypeScript code (lazy-loading.modules.ts):

import { NgModule, Component } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
@Component({
    selector: 'app-about',
    template: '<h3>About Active!!!</h3>',
})
export class MyComponent  {}
const routes: Routes = [
    { path: '', component: MyComponent }
];
@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class RootRoutingModule { }
@NgModule({
    imports:      [ RootRoutingModule ],
    declarations: [ MyComponent ]
})
export class SecondModule { }

HTML code (app.component.html):

<h2> Example of Angular Lazy Loading</h2>
    <a routerLink='Home'>Home</a>
    <br>
    <a routerLink='About'>About</a>
    <router-outlet></router-outlet>

Click here to check the working of the code above.

If possible, avoid lazy loading paths your users frequently visit. Reduce the size of your chunks as much as possible.

Moreover, when a lazy loaded route is retrieved, use router states to show a loader or animation so that your users don’t think your application is lagging.

Muhammad Adil avatar Muhammad Adil avatar

Muhammad Adil is a seasoned programmer and writer who has experience in various fields. He has been programming for over 5 years and have always loved the thrill of solving complex problems. He has skilled in PHP, Python, C++, Java, JavaScript, Ruby on Rails, AngularJS, ReactJS, HTML5 and CSS3. He enjoys putting his experience and knowledge into words.

Facebook

Related Article - Angular Module