20
DecWhat is Lazy Load in Angular With Example?
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
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
- Node.js must have been installed.
- 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
Parameters | Lazy Loading | Eager Loading |
Resource Initialization Timing | Delays initialization until needed | Initializes or loads resources as soon as code is executed or page is loaded, regardless of immediate requirement. |
Impact on Performance | Reduces initial load times, ideal for speed and responsiveness, but may introduce delay when accessing resources for the first time | Ensures immediate availability of resources, smoother post-load experience, but longer initial load times |
Bandwidth and Memory Usage | loads only required resources, beneficial for mobile users or limited bandwidth | Consumes more bandwidth and memory upfront by loading all resources, which is less efficient for limited resources. |
Complexity and Maintenance | More complex logic for on-demand loading, increasing code maintenance complexity | Simpler to implement, with no additional loading logic, but may need optimization for the initial resource load |
Application Scenarios | Suited for applications with many features/content, ideal for mobile devices or varying network conditions | Appropriate 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
FAQs
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.