Angular CLIAngular JS TutorialsAngular TutorialsLazy LoadingWeb Development

How to Lazy Load Modules in Angular 8

In this tutorial, we will discuss about lazy load modules in Angular 8. Angular is one of the most popular JavaScript Framework for building front end of application. You can easily single page application using Angular. But what to do if you want to run a huge application in Angular. Main question arises with this thought is

  1. Will Angular still loads fast with huge bundles of JavaScript code ?
  2. Will Angular survive with huge traffic of visitors.

Answer is Yes, Angular can run much faster either your application is very big. Angular has inbuilt features to reduce load of huge JavaScript code on browsers. One of these feature is Lazy Load.

Lazy Load Modules in Angular 8

Lazy Load basically means breaking JavaScript execution in smaller chunks. These small chunks are trigger based on your route path. These small chunks are nothing but small files that contains JavaScript code for your each module. This module act as a feature module in your application.

How to Lazy Load Modules in Angular 8 ?

For making your application to lazy load modules in Angular 8. You have to analyze which sections need a separate module in your application.

For example

If you have an eCommerce application in which you have menu items

  • Product Gallery
  • Product Details
  • Home Page to show slides
  • About Us
  • Contact Us
  • Login/Register
  • And other information pages like terms and condition etc.

Technically, if a visitor loads your application then all JavaScript bundles related to all sections will load at one time. Due to which it can take more execution time. To reduce that much load divide all pages in different modules, so you can lazy load modules in Angular.

Because of Lazy Load, different sections will have different module. And all these module will have their JavaScript code in separate chunks file.

When you build your application, you will see lot of files created based on each module.

For creating new application click here

Steps to Lazy Load Modules in Angular 8

Suppose you are creating one feature module for about us page then your routing path without lazy load and module will be

{
    path: 'about-us',
    component: AboutUsComponent
}

Above code can be found in your app.routing.ts file or your routing module file.

Create a folder modules inside src/app folder and then create about-us folder inside it.

Modules Folder inside src/app
About us folder inside modules folder.

You can give any name to your folder but make sure it is easy to find files. This folder naming is only for reference to make it more understandable.

Now go to your root folder of your application then Shift + Right Click. Open command prompt window or Power shell window as shown below

Open Power Shell or Command Prompt Window

Now write command as shown below and in above picture

ng generate module modules/about-us

in above command modules/about-us is the path where actual module file will be generating along with routing file. Hit Enter and then wait until you get message of Success.

Every module you generate using command line or power shell will have its own routing file. This routing file is nothing but act as child route in which you can define sub paths of that module.

Load Your Modules using your main routing file

Once you are done with above steps you will see some files like this

Lazy Load Modules in Angular

I have created one folder components in which all components related to about us module exists.

Inside about-us.module.ts you will see code as shown below

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { AboutUsRoutingModule } from './about-us-routing.module';
import { AboutUsComponent } from './components/about-us.component';

@NgModule({
  declarations: [AboutUsComponent],
  imports: [
    CommonModule,
    AboutUsRoutingModule
  ]
})
export class AboutUsModule { }

You can see AboutUsRoutingModule is already imported in it.

Inside AboutUsRoutingModule you will see code as shown below

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AboutUsComponent } from './components/about-us.component';

const routes: Routes = [
  {
    path: '',
    component: AboutUsComponent
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class AboutUsRoutingModule { }

In above code you can see RouterModule.forChild(routes) but in main routing you will see RouterModule.forRoot(routes).

Now open your main routing file, in my case it app-routing.module.ts and it is inside src/app folder.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LayoutComponent } from './layout';
import { HomeComponent } from './modules/home/components/home.component';

const routes: Routes = [
  {
    path: '',
    component: LayoutComponent,
    children: [
      {
        path: '',
        loadChildren: () => import('@modules/home/home.module').then(m => m.HomeModule)
      },
      {
        path: 'about-us',
        loadChildren: () => import('/src/modules/about-us/about-us.module').then(m => m.AboutUsModule)
      }
    ]
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

You can see path for about-us in which loadChildren parameter is there. Inside this parameter you can see complete path about us module is dynamically imported.

When you hit URL yourdomain.com/about-us then your main routing file trigger about-us module. And this about us module will trigger about us routing module.

All paths after about-us like

yourdomain.com/about-us/page1

will be defined inside about-us routing module instead of app-routing.module.ts.

Currently for me there is no path after about-us that’s why I am using

{
    path: '',
    component: AboutUsComponent
  }

Flow of Lazy Load Module and Benefits

Without Lazy Load, you will directly importing components inside main routing file due to which all initialization takes place at first reload but not in lazy load. In lazy load, if you hit URL then your main routing file start importing module related to your path. After importing Module, it execute dynamically about-us-routing.module.ts and then it loads the component based on path.

In this way you don’t have to wait for the execution to complete. You can further divide it into sub modules as per requirement to reduce loading and execution time.

For Testing your lazy load of Module in Angular 8 just open your application navigate to path into which you have imported module.

Before opening that right click and open Inspect and then go to Network tab.

You will see something as shown below when you lazy load some module

Lazy Load Modules in Angular

Anil Mehra

I am Anil Mehra, a passionate, workaholic and a Full Stack Tech Savvy Programmer with true north towards growth. I have worked on 256 live projects in MNC. I am expertise in the field of Programming, Server Management, SEO, Blogging and SMO...

Related Articles

Leave a Reply

Your email address will not be published.

Back to top button

Adblock Detected

Please turn off Ad blocker to view website