How To Implement Lazy Loading In Angular?

How To Implement Lazy Loading In Angular?

03 Oct 2022
How To Implement Lazy Loading In Angular?

Lazy Loading in Angular:

Lazy loading is a method that allows the user to load the javascript components only when their corresponding routes are active or being hit. It enhances the performance and speed of the application by dividing the app into various bundles. Lazy loading speeds up the application load time by dividing it into various bundles and loading them on request.


Why Lazy Loading is required?

Lazy Loading is needed when the user wants to load only those routes whose UI is being displayed. For example, if the user is on the Home page, he would not prefer to load the Contact Us and About Us pages.


Advantages of Lazy Loading:

  • High performance on initial load in bootstrap time.

  • Modules are arranged according to their functionality.

  • Initiate the code module by navigating to the route.

  • Helps reduce the load time.

  • Modules are loaded on demand and when the user navigates to their routes.

  • Decreases resource consumption.


Let's understand the steps to implement Lazy Loading in the Angular application.

Step 1: Create a demo app.

$ ng new lazy-load-demoapp --routing

This will create a new Angular project with a default route module and all the essential dependency files.

Step 2: Create a Lazy Loading module and separate routing file.

$ ng g module about-lazy-loading --routing

Step 3: Create new components to exhibit Lazy Loading.

$ ng g components about-us

Step 4: Add links and routes

             1. Add a link in the header of the route on which the user will implement Lazy Loading.

             2. Set up the route in lazy-loading-routing.module.ts.

 Step 5:  Configure the LazyLoad Routes.

Define Routes using the loadChildren attribute in the app-routing.module.ts file.

Step 6: Start the Application

After completing all the basic steps for Lazy Loading, start the application to understand how lazy it is.

Run ng serve to start the application.

  • open the browser,

  • enter URL local:4200 in the browser console

  • then go to the Network tab.


In the network tab in the Chrome Dev Tools, the user can check the files that are loaded:


Similarly, in the Network tab, the user can see:

The application loads the main.js with all the components of the application.

Now, click on the created link to see the first module to be loaded.

The link will redirect and the Network tab will resemble this. And it is visible that the About Lazy-load module has loaded only after the about link is clicked.

This blog highlights how important Lazy-Load modules in Angular are and how it improves the web app performance effectively.

Leave a comment: