How to Implement Lazy Loading in Angular?

How to Implement Lazy Loading in Angular?

06 Apr 2021
0 Comments
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 accelerates the appliance load time by dividing it into various bundles and loading them for the asking.

 

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-demo app-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 link and routes

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

app.component.html

 

  1. 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 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 AboutLazy-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: