Lazy Loading In Angular

Let’s have a look on lazy loading in angular, it also often referred as code splitting, as the name suggests splitting out code into multiple small chunks. So what all it does?

Let’s have a look at lazy loading in Angular. It's also often referred to as code splitting, as the name suggests splitting out code into multiple small chunks. So what does it do? 

Well, it allows the splitting of the code into smaller chunks and can be called anytime, whenever it's required.

Let’s dive deep into what code splitting and lazy loading are.

Code Splitting

Code splitting allows us to break our application into smaller modules (chunks). Therefore, in a nutshell, our application becomes many small applications, typically called chunks. These small chunks can be called on demand whenever required.

Lazy Loading

Once we have divided our application into smaller chunks, lazy loading calls the chunks when they are required. It helps us to increase the performance of the application, as we are just downloading a part of our application whenever required. In Angular this is achieved through the router.

But wait… why do we need this?

Let’s say you have an enterprise level application, “My MIS”. It’s a huge Management Information System that has various modules like HR, Documentation Generator, Transport, Finance etc.

You also have hierarchical logins for different types of users. In a standard case when you login into the application through a login page or when your application startup page gets loaded, it actually downloads all the dependent Angular modules and dependencies. Suppose your HR Module has four dependencies and the transport module has three dependencies. So on the startup page (on load page) it will download all the dependent modules in one go and load everything at once.

It consumes a huge network bandwidth and makes your application slow. Implementing the lazy loading helps us to decrease the startup time of application and our application does not need to load everything at once. The modules will only be loaded when the user navigates to that module or route.

Let us take a module structure as below,

module structure

Normally in this scenario angular will load all the modules at once when the application starts, and this is exactly where the lazy loading comes into play. Therefore, with lazy loading you can start the app module first.

app module

And depending upon the user’s route it demands the next module and loads it. Let’s say we now want transport module, then it will be:


transport module


Now the user navigates to HR module, then it will be:


HR module


Now as we are not loading all the modules on one go it will decrease the startup time and will make our application more efficient.