Lazy Loading in Angular

Lazy Loading in Angular

03 Jun 2024
Intermediate
840 Views
10 min read
Learn via Video Course & by Doing Hands-on Labs

Self-Paced Angular Certification Course

What is Lazy Loading?

Lazy loading in Angular is a technique to load only the required pages. Isn't it amazing? You might have faced difficulty viewing pages having a lot of media elements. It's because as soon as the application opens all the modules, components, images, and videos start loading immediately. This is eager loading. Lazy loading is the opposite of it. It will load the elements when you are about to scroll them thus saving bandwidth and load time.

In this Angular tutorial, we'll learn this important technique thoroughly. We'll see the implementation, benefits, use cases, etc. of lazy loading along with the comparison of lazy loading and eager loading. So, go along with us and understand the concept.

Read More: Top 50+ Angular Interview Questions & Answers

How Lazy Loading Works?

Angular performs lazy loading by using the Angular Router. When a user navigates to a specific route associated with a lazy-loaded module, Angular fetches and loads that module immediately

How Lazy Loading Works?

To lazy load Angular modules, use loadChildren in your AppRoutingModule routes configuration as follows.


const routes: Routes = [
  {
    path: 'items',
    loadChildren: () => import('./items/items.module').then(m => m.ItemsModule)
  }
];    

Add a route for the component in the lazy-loaded routing module.


const routes: Routes = [
  {
    path: '',
    component: ItemsComponent
  }
];   

Don't forget to remove the ItemsModule from the AppModule.

Implementing Lazy Loading in Angular

Prerequisites

  1. Node.js must have been installed.
  2. Basic knowledge of Angular

1. Create an Angular Project

Use the Angular CLI to create your project. Install the CLI using npm by running the command:


npm install -g @angular/cli

Now create a project named Lazy Loading Example


ng new lazy-loading-example --routing

The Angular project named Lazy Loading Example was created. The src/app folder contains the code for your app. The main routing file, app-routing.module.ts is located in this folder.

2. Create a Feature Module with Routes

This feature module will load lazily. Run the command


ng generate module blog --route blog --module app.module

This command creates a module named BlogModule, along with routing. You can see this in src/app/app-routing.module.ts:


import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [ { path: 'blog', loadChildren: () => import('./blog/blog.module').then(m => m.BlogModule) }];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { } 

In the above code, the following line defines the routes for lazy loading:


const routes: Routes = [ { path: 'blog', loadChildren: () => import('./blog/blog.module').then(m => m.BlogModule) }];

The module defines its child routes, such as blog/**, in its routing.module.ts file. The blog module you generated looks like this:


import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BlogComponent } from './blog.component';

const routes: Routes = [{ path: '', component: BlogComponent }];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class BlogRoutingModule { }

The above routing file contains a single route, ''. This resolves for /blog and points to the BlogComponent. You can add more components and define those routes in this file.

For example, to add a component that would pull details about a particular blog post, you could create the component with this command:


ng generate component blog/detail

This generates the component for the blog detail and adds it to the blog module. To add a route for it, you can add it to your routes array:


const routes: Routes = [{ path: '', component: BlogComponent },
                        {path:"/:title",component: DetailComponent}];

Verify Lazy Loading

You can easily check whether lazy loading is working or not. For this, run the below command:


ng serve

You will get the following output

You can observe in the above output that Initial Chunk Files are loaded when the page first loads. Lazy Chunk Files are lazy-loaded. The blog module is listed in this part.

Benefits of Lazy Loading in Angular

  • Improved initial load time: As everything doesn't load at the beginning the application loads fast.
  • Less memory usage: Only required modules and components are loaded hence less memory consumption.
  • Organized code: There is modularity in the code hence easy to maintain.

Lazy Loading Vs. Eager Loading

ParametersLazy LoadingEager Loading
Resource Initialization TimingDelays initialization until neededInitializes or loads resources as soon as code is executed or page is loaded, regardless of immediate requirement.
Impact on PerformanceReduces initial load times, ideal for speed and responsiveness, but may introduce delay when accessing resources for the first timeEnsures immediate availability of resources, smoother post-load experience, but longer initial load times
Bandwidth and Memory Usageloads only required resources, beneficial for mobile users or limited bandwidthConsumes more bandwidth and memory upfront by loading all resources, which is less efficient for limited resources.
Complexity and MaintenanceMore complex logic for on-demand loading, increasing code maintenance complexitySimpler to implement, with no additional loading logic, but may need optimization for the initial resource load
Application ScenariosSuited for applications with many features/content, ideal for mobile devices or varying network conditionsAppropriate for smaller applications where all resources are essential from the start, like certain desktop applications.

Lazy Loading in Angular: Examples and Use Cases

  • Feature Modules

    Break down your application into feature modules (e.g., user management, shopping cart).

  • Large and Infrequently Used Features

    If a feature is complex or rarely accessed (e.g., admin dashboard), lazy load it to reduce initial load time.

  • Dynamic Content

    Load content based on user interaction (e.g., clicking a tab to display a specific section).

  • Code Splitting for Improved Build Times

    Lazy loading modules help break down the overall application bundle for faster build and development cycles.

Summary
As a developer, you must know the techniques to make your application user-friendly in all possible ways. Angular is a single-page application and hence it can take a long time to load if it's big. Lazy loading is an effective strategy to overcome this barrier. We learned about how to implement this technique to optimize your Angular applications. For a good hands-on, consider our Angular Certification Course.

FAQs

Q1. What is lazy loading in Angular?

 Lazy loading in Angular is a design pattern that delays the loading of feature modules until they are needed, improving initial load time and application performance. 

Q2. Why should I use lazy loading in my Angular application?

 Use lazy loading in your Angular application to improve performance by loading modules only when needed, reducing initial load time and enhancing user experience. This approach optimizes resource usage and speeds up navigation within the app. 

Q3. How do I implement lazy loading in Angular?

 To implement lazy loading in Angular, use the loadChildren property in your route configuration to load feature modules dynamically. Ensure your feature modules are defined using the NgModule decorator and set up with routing. 

Q4. Can I lazy load individual components in Angular?

Yes, in Angular, you can lazy load individual components by using Angular's loadChildren with Angular modules and loadComponent for standalone components.

Take our Angular skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
ASP.NET Core ProjectOct 19SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
ASP.NET Core Certification TrainingOct 20SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this