Lazy loading concept in Angular

kirushanthy jeyarajah
3 min readJan 16, 2021

Hello everyone in this article I give small information about lazy loading concept

Why we need the lazy loading ?

Lazy loading helps decrease load time. It is a routing technique in which components load in browser only when their corresponding route is activated. The main aim of lazy loading is to improve the performance of the Angular app by restricting the unnecessary loading of components.

How does lazy loading works?

When we navigate to the web page that implements lazy loading, the request made to the host server and all of the packets, or chunks, are sent in response and stored in the browser cache, lazy loaded modules included. After , with the exception of the lazy loaded modules, the packets are assembled, parsed, and loaded, rendering the page

first we need the create the Angular Application

ng new lazy-app — —routing

using above command we are telling the CLI to create empty project with an additional routing module.

then create out first component — ng g c first (when we create the component its automatically imported in app.module)

Let’s go into app-routing.module.ts and add this component to the main route

app-routing.module.ts

next we will create the lazy module for our app, which will be lazy-loaded. use ng g m lazy this command to get the lazy module.

We also create a component which will be the root component for our new lazy-loaded module: we just tell the CLI the path to our module and it will create our files for us, importing them in the correct module.

ng g c lazy/second

We just need to declare a new set of routes for our lazy module, which will display our SecondComponent.

lazy.module.ts

Next we need to add new route for our LazyModule in our app-routing.module.we will specify the path to the module like below.

app-routing.module.ts

And finally we add the routing in our html file.

app.component.html

when we click the “second” link the we navigate from AppModule to LazyModule.

we can open the browser inspector and go to the Network tab and see that once you navigate to the lazy route, a new chunk.js file will be loaded asynchronously.

Thank you for reading this Article 😊 .I hope all are safe and healthy.

--

--