Guide to Lazy loading in Angular

Lazy loading is the technique where angular loads the Modules only on a need basis rather than all at once. It is also called on-demand loading. By default, Angular Loads the modules eagerly. Lazy Loading of Angular Modules reduces the initial load time of the app. We use the loadChilden method of the Angular Router to lazy load them when the user navigates to a route. In this article, we will show you how to implement lazy loading

Why Lazy load?

The Angular apps get bigger in size as we add more and more features. The Angular Modules help us to manage our app by creating separate modules for each new feature. But, as the app gets bigger in size, slower it loads. That is because of angular loads the entire application upfront.

The slow loading app does not leave a good impression on the user. By Loading only a part of the app (i.e lazy loading), the app appears to run faster to the user. The faster loading app gives you a performance boost and also results in a good user experience.

How Lazy loading works

In Angular, the Lazy loading works at the module level. i.e. you can lazy load only the Angular Modules. We cannot lazy load the Individual components.

The Lazy loading works via the Angular Router Module. The loadChildren method of the Angular Router is responsible to load the Modules

We define the modules which we want to lazy load, when we define the routes. Starting from the Angular 8, we have a new syntax for lazy loading.

The admin is the path is the URL path segment to the AdminModule. The loadChildren is where we configure the Lazy Loading.

loadChildren

We need to provide call back function to loadChildren argument. The call back must load the AdminModule. We use the dynamic import syntax using the import method. The import method loads the module from the path, which we provide as the argument to it.

When the user navigates to the admin URL or to any of its child routes like admin/dashboard, the router will fetch the AdminModule and loads the routes and components of the AdminModule

The lazy loaded module loads only for the first visit of the URL, it will not load when we revisit that URL again.

When we define an AdminModule to lazy loaded, the angular creates a separate bundle for the entire module.

If you are using Angular 7 or lower versions, then use the following syntax

The loadChildren accepts the value as string. The string is split into two sections separated by #.The first part is the full path to the module file (without the ts extension). In the example above ./admin/admin.module points to admin.module.ts file. The second part is the export class name of the Module. i.e AdminModule

{path: "admin", loadChildren:'./admin/admin.module#AdminModule'},

Angular Lazy Loading Example

Let us build a simple app. The app will have two modules. One is SharedModule which we load eagerly. The other module is AdminModule. First, we load the AdminModule eagerly and later we we update it to use the Lazy Loading.

Admin Module

The AdminModule contains three components DashboardComponentRightsComponent;UserComponent. The Module contains, three routes defined as children of Admin Route defined in the AdminRoutingModule

The above routes are registered using the forChild method()

The Complete source code of AdminModule is as below

src/app/admin/pages/dashboard/dashboard.component.ts

src/app/admin/pages/rights/rights.component.ts

src/app/admin/pages/user/user.component.ts

src/app/admin/pages/index.ts

src/app/admin/admin.routing.module.ts

src/app/admin/admin.module.ts

Shared Module

The SharedModule contains HeaderComponent & FooterComponent. The HeaderComponent contains the navigation menu. 

src/app/shared/layout/footer/footer.component.ts

src/app/shared/layout/footer/footer.component.html

src/app/shared/layout/header/header.component.ts

src/app/shared/layout/footer/footer.component.ts

src/app/shared/layout/header/header.component.css

src/app/shared/layout/index.ts

src/app/shared/shared.module.ts

src/app/shared/index.ts

Root Module

The Root Module uses the forRoot method to register the routes. Right now it does not contain any routes. It also imports the AdminModule

Test the app by running it.

When you run the ng Serve command, you will see that it generates the five JavaScript files ( called chunks) main.js, polyfills.js, runtime.js, styles.js, vendor.js. As you add more and more features those are added to the main.js file

The Chunks generated by Angular CLI

Ctrl + Shift + I to open the chrome developer console and and open the network tab. Run the app and you will see that all the chunks are loaded upfront

Eagerly loading Angular Modules Example

Lazy loading the AdminModule

To Lazy Load AdminModule, First we need to add the following route in the AppRoutingModule. This route instructs the router load the AdminModule from the path ./admin/admin/module.ts when user navigates to the Admin route

Next, we need to remove the import of AdminModule from the AppModule. If you did not do it, the module will be loaded eagerly.

Finally, We need to change the route definition in the AdminRoutingModule. We have removed the parent route admin as it is now moved to the AppRoutingModule. Since this is a lazy-loaded module, the routes we specify will automatically become the child route of admin

Now, when you run ng serve command, you will notice the admin-admin.module.js file. The Angular compiler generates a separate js file for each lazy loaded module. This file is loaded only when it is needed by the router.

The Lazy loaded module has its own chunk

You can test it by running the app. You can notice that admin-admin.module.js is not loaded when you run the app. It is loaded only when you click either on Dashboard, user or rights menu.

Lazy Loading Angular Module example

Services in Lazy Loaded Module

We need to be careful when we create a service or provide a services in Lazy loaded module.

Any Service defined in the Lazy Loaded Module, will not be load until the user navigates to that module. Hence we cannot use them anywhere else in the application.

The Angular creates a separate injector for the lazy loaded module. Therefore, any service we provide in the lazy loaded module gets its own instance of the service.

Hence create a service in the lazy loaded module, only if it is used within the lazy loaded Module. Else consider moving it to the AppModule or a special CoreModule. For More read Folder structure in Angular

Dos and Dont’s of Lazy loaded Modules

Do not import lazy loaded modules in any other modules. This will make the angular to load the module eagerly and can have unexpected bugs.

Be careful when you import other modules in the lazy loaded module. If the other modules providers any services, then the lazy loaded module will get a new instance of the service. This may have unintended side effects, if the services are intended to be app-wide singleton

Summary

The Angular Modules and lazy loading of those modules is one of the best features of angular. You should load only the SharedModule & CoreModule upfront and lazy load rest of the application. 

1 thought on “Guide to Lazy loading in Angular”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top