What is Lazy Load in Angular With Example?

What is Lazy Load in Angular With Example?

25 Oct 2024
Intermediate
1.17K Views
10 min read
Learn with an interactive course and practical hands-on labs

Self-Paced Angular Certification Course

What is Lazy Loading in Angular?

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 in Angular 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.

How to Implement 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 Course.

FAQs

 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. 

 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. 

 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. 

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
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this