Lazy Loading in Angular:
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:
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
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.
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.