DEV Community

Guddu Patel
Guddu Patel

Posted on

Modules Loadings in angular

Eager loading and lazy loading are primarily two types of loading in angular . One more type of loading called pre-loading  also exist , These loading strategies determine how and when modules are loaded in your application. Let’s explore these loading types with examples

1 Eager Loading:

Eager loading is the default loading strategy in Angular. This method loads every module when the program launches, whether or not it needs them right away.

2 Lazy Loading:

Modules are loaded using the lazy loading mechanism as and when they are required. This can speed up the application's loading time and drastically reduce the initial bundle size, especially for big apps.

3 Pre-Loading:

Feature Modules under Pre-Loading would be loaded automatically after the application starts.

Let check it into detail

Eager Loading:

As we now now this loading technique loads all the module at beginning of the application i.e at stating time only without worrying about the module is even required or not . This may result in bigger initial bundle sizes, which might affect how quickly the program loads.

Advantages:
All  module are loaded at beginning, No worry of loading module again and again.
It give surety of running program smoothly as all module already loaded
Disadvantages:
All  module are loaded at beginning, which make larger bundle size to be loaded so slower in speed at initial.
For big and complex application it might break due to heavy load of bundle.

When to use Eager loading

Small size applications. wherein the program will be quicker and more receptive to process requests if all modules are loaded before the application launches.
Required feature and core modules for the application to launch. The first page's components, interceptors (for authorization, authentication, and error handling, etc.), error response components, top-level routing, localization, and other features might all be included in these modules. To ensure that the program runs well, regardless of its size, we only need to load these modules with great anticipation.

Example:


import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AccountComponent } from './account/account.component';
import { CustomersComponent } from './customers/customers.component';
const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'home', component: HomeComponent },
  { path: 'account', component: AccountComponent },
  { path: 'customers', component: CustomersComponent },
  { path: '**', component: HomeComponent }
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }


Enter fullscreen mode Exit fullscreen mode

from above code snippet we can is illustrate that, All component are going to be loaded at the beginning even when application start it will view only home page but other component like account section may or may not be visited by user but it still loaded at beginning this process of loading make our application slower and take more space.

Lazy Loading:

This technique say, be lazy mean do work only when its required similarly, Modules are loaded using the lazy loading mechanism as and when they are required. This can speed up the application's loading time and drastically reduce the initial bundle size, especially for big apps.

Advantages:
Required  module are loaded at beginning, No worry of loading all module.
Smaller bundle size so faster loading
best suited for big and complex application because of modularity loading
Disadvantages:
Carefully routing need to be setup so required module for stating app should must be loaded.
Not necessarily all module can be lazy loaded

When to use lazy loading:
Applying lazy loading in this circumstance is a rather easy and uncomplicated process. When a large-scale web application launches, all other modules that are not needed can be loaded idly.
Vast and complex application which have multiple modules.

Example:


//App.module.ts
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


//app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
  {
    path: 'orders',
    loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule)
  }, 
];
@NgModule({
  imports: [
    RouterModule.forRoot(routes)
  ],
  exports: [RouterModule],
  providers: []
})
export class AppRoutingModule { }
// orders-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { OrdersComponent } from './orders.component';
const routes: Routes = [
  {
    path: '',
    component: OrdersComponent
  }
];
@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class OrdersRoutingModule { }
// order.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { OrdersRoutingModule } from './orders-routing.module';
import { OrdersComponent } from './orders.component';
@NgModule({
  imports: [
    CommonModule,
    OrdersRoutingModule
  ],
  declarations: [OrdersComponent]
})
export class OrdersModule { }

Enter fullscreen mode Exit fullscreen mode

From above snippets we can illustrate that the required module will load on the stating of application and the module which are specified load children will be dynamically load when the user visit the given route, Until user visit the specified route that component are not required and mot load into the memory which make our app faster with smaller bundle size

Pre-Loading:

Its one of the loading strategy which rarely used Compared with Eager Loading and Lazy Loading, Pre-Loading is not so much frequently used in web application development. Feature Modules under Pre-Loading would be loaded automatically after the application starts. All the module are specified to be loaded after application start in advance.

Advantages:
All  module are loaded one by one as specified  after application started.
It load the component with might user visit next in advance
Disadvantages:
All  module are loaded at beginning, which make larger bundle size to be loaded so slower in speed at initial.
For big and complex application it might break due to heavy load of bundle.
When to use  pre-loading:

1: Medium size application, Since the remaining modules that are needed to execute the program will load later, we can make the application start faster in this circumstance. Also, since the program will load all of these modules once it has begun, it will respond to user requests more quickly than if it used the lazy loading technique.

2: After the program launched, there are a few particular modules that consumers are probably going to employ. We can pre-load certain feature modules in this case while continuing to lazy load other modules.

  1. If probability of next component to be visited is clear then use preloading

There are 2 strategy for pre-loading module:

a) Preloading all module

//App-routing.module.ts
import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";
import {PreloadAllModules } from '@angular/router';
const routes: Routes = [
  {
    path: "login",
    loadChildren: () => import("./auth/auth.module").then(m => m.AuthModule),
    data: { preload: true, delay: true, time: 5000 }
  },
];
@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      preloadingStrategy: PreloadAllModules
    })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule {}
Enter fullscreen mode Exit fullscreen mode

b)Prealoading With custom strategy

//App-routing.module.ts
import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";
import { CustomPreloadingStrategyWithDelay } from "./core/custom-preloading-strategy-with-delay";
const routes: Routes = [
  {
    path: "login",
    loadChildren: () => import("./auth/auth.module").then(m => m.AuthModule),
    data: { preload: true, delay: true, time: 5000 }
  },
];
@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      preloadingStrategy: CustomPreloadingStrategyWithDelay
    })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule {}
//custom-preloading-strategy-with-delay.ts
import { PreloadingStrategy, Route } from "@angular/router";
import { Injectable } from "@angular/core";
import { Observable, of, timer } from "rxjs";
import { flatMap } from "rxjs/operators";
@Injectable({
  providedIn: "root"
})
export class CustomPreloadingStrategyWithDelay implements PreloadingStrategy {
  preload(route: Route, load): Observable<any> {
    const loadRoute = (delay, time) =>
      delay ? timer(time ? time : 1000).pipe(flatMap(_ => load())) : load();
    return route.data && route.data.preload
      ? loadRoute(route.data.delay, route.data.time)
      : of(null);
  }
}

Enter fullscreen mode Exit fullscreen mode

From above code snippet we can illustrate we can load any module in advance if we are predict that the user will visit next page  , It can be done by specifying the preload value with module while route configuration.

If we are not sure of next module to be pre load then we can preload all module configuration can done, Or if we are good idea of page to be visited in some particular order then we can use custom preload strategy to load module

Top comments (0)