Lazy Loading in Angular

Hello Readers,

In this article, we are going to cover:

· Lazy Loading of Feature Modules

· Different Loading Strategies

· Custom Preloading Strategy for Lazy-Loaded Modules

Lazy Loading of Feature Modules:

Lazy loading is the process of loading some features of your Angular application only when you navigate to their routes for the first time! This can be useful for increasing your app performance and decreasing the initial size of the bundle that would be downloaded to the user’s browser.

A Lazy loaded module can have one or more components inside it. But remember the module which you are going to lazy load needs to be a different module then your Root Module.

So, for example, if you want to lazy load the Product component then you have to create a Product module with all the components it needs, along with its own routing file and module file.

We all know lazy loading is one of the most useful concepts of Angular Routing so let us see how to implement it by this simple example.

Firstly, I have created a new blank Angular Application with Angular-CLI and then I have added 3 components to it named Home, Product, and Employee. I have also created one component for Menu. As I have used Menu component in this example so I am using router-outlet to show the data of component which are going to be loaded outside that Menu area.

Okay, so below is the code for menu.component.html and app.component.html respectively.

So to start with lazy loading, you can go to the route configuration (app.routing.ts) and use the property loadChildren.

Let us see the syntax of loadChildren property:

const arr: Routes = [

….

{ path: ‘employee’, loadChildren: ‘./employee/employee.module#EmployeeModule’}

….

];

The loadChildren property accepts a string value that contains the route to your lazy-loaded module followed by a Hash symbol and then the class name of that module.

Check the whole app.routing.ts file as below:

Here, notice that we are not going to import those modules which we want to lazy load. In our case, we want to lazy load Employee and Product modules so we do not write import statements for them.

So when the route gets activated, this loadChildren property will get activated and it will load the requested module by its given path. Then it will load the requested component and display that component’s template (Html).

The next task is to configure our Routes for these feature modules.

So, as I said earlier we need to create separate Routing file and Module file for each module whichever we want to lazy load.

So below is the code for employee.routing.ts file:

So here we are actually giving a path to all the components of Employees Module created. This will actually find out the whole path of any component.

If you are having more than one component in one Module, Like Product Module in our example then it can be done as below:

And finally, create the Module files for each module. Here we need to create module files for both Employee and Product.

So, the last and important thing is to make changes in the app.module.ts.

Here in app.module.ts we will only load the Home Component. Because importing any component to this file means that it will load all these components when we run this application in the browser. But here we want some of the modules to be load only on demand or we can say when we navigate to those modules.

So this way our lazy-loaded modules can be accessed.

Now, once we have a lazy-loaded, run this Application in the browser and go to the Network tab in Console to see which files are generated.

Here you can see no files regarding Employee and Product Modules are there. This means that when application gets loaded in the browser it will load only necessary files it requires but now when we click on the Employee Menu then we can see the changes in Network tab as below:

As you can see new bundle file (chunk) is generated for Employee. So this entire Employee module gets loaded in the browser when the user navigates to that particular route for the first time. This is how lazy loading gets implemented using loadChildren property.

Similarly, you can also check the Product module:

Different Loading Strategies:

Basically we can load any Module in three different ways:

· Eagerly

· Lazily

· Preloading

Eager loading:

By default, every Angular Application uses this loading strategy. In Eager Loading all the feature modules are loaded before the application gets started along with the root (App) module. So if you are having small-sized application then you can use this strategy because it will require all the modules and its dependencies to be ready when you are running the application for the first time.

To implement the Eager Loading, you have to import the modules in app.module.ts file just like what we do with any normal Angular Application.

Lazy Loading:

As we have seen earlier if we use lazy loading then we can render the module on demand when needed. Also if the application size is becoming larger with many feature modules, loading everything eagerly will make application slow. So instead we can use lazy loading.

Preloading:

By preloading, the application will start loading chunks of modules before needed. This means modules do not wait to get loaded until the user navigates to their routes. Modules can be loaded in the background asynchronously just after the application gets started.

For this strategy, Angular provides PreloadingStrategy abstract class. And it has two subclasses: PreloadAllModules and NoPreloading.

  • NoPreloading — default behavior that doesn’t preload any modules.
  • PreloadAllModules — all modules are preloaded as soon as possible.

To use any of the above strategies what you have to do is specify the strategy in your app-routing.module.ts as shown below:

1) import { RouterModule, Routes, PreloadAllModules } from ‘@angular/router’;

2) Now inside @NgModule’s imports :-
imports: [


RouterModule.forRoot(ROUTES,
{ preloadingStrategy: PreloadAllModules })
],

Let’s see a quick example of how we can use Preloading with Customization!

Custom Preloading Strategy for Lazy-Loaded Modules

If you do not want all lazy loadable modules to be preloaded then you can implement your own preloading strategy.

Ideally, we would like to preload the core features or most commonly used modules of our app. This will allow core features to load immediately as well as we will lazy load other features, which are less used, on-demand when the user clicks the link.

So for this, we will define and export a CustomPreloading class that implements PreloadingStrategy class.

(Note: For Custom Preloading, I have created another fresh Angular Application which is having Dashboard, Product and Contact modules)

As you can see above we have implemented the PreloadingStrategy class so we need to override the Preload() method of that particular class. This method receives the active route as a parameter. With this route, it will look at the Data object was set or not. If set, then it will load that module otherwise returns null means it will not preload.

Now in our app.module.ts, we will import the PreloadingStrategy class, and define that the RouterModule should use the CustomPreLoading as our preloading strategy. After that in providers array, we will provide the path of this custom preloading file.

Now it’s time to set the Routes:

For customized preloading, we have to specify the Data object to the path that we define. This Data object is having property preload which should be set to true. So, the syntax is: data: {preload: true}

So, According to our CustomPreloading strategy implementation, if the value of data.preload: true then we are confirming that module is to be preloaded and if the preload value is not true then module won’t be preloaded.

Okay, so finally run the Application and check the Console’s Network tab.

Here notice that if you are loading the App first time, it will load the Dashboard module and Contact Module both. Because we have Preloaded Contact Module so its chunk gets loaded initially.

And now click on the Product Menu. And you will notice that chunk for that get loaded runtime when you actually visit that route.

Thank you for Reading!

You can find full code for this here:

Lazy Loading Demo

Custom Preloading Strategy

Jinal Shah is corporate trainer on different technology like node.Js, Angular,Ionic 2, BOT Framework etc.