DEV Community

KrishnaSai Polanki
KrishnaSai Polanki

Posted on • Edited on

Preloading Strategies in Angular

Let's learn about different preloading strategies in Angular.

In Angular whenever we click on any route the angular router first checks that particular module bundle is available or not in the browser's cache, if not it will go and get it. To make things faster here, angular provides a technic or strategy to pre-fetch or pre-load the modules. We can do this in 3 ways

1.NoPreloading: This is the default behavior and does not preloads any module except the main app module.

RouterModule.forRoot(appRoutes, { preloadingStrategy: NoPreloading }),
Enter fullscreen mode Exit fullscreen mode

2.PreloadAllModules: Will load all the modules.

RouterModule.forRoot(appRoutes, { preloadingStrategy: PreloadAllModules }),
Enter fullscreen mode Exit fullscreen mode

3.Custom: Here we can do the custom preloading based on the application modules. (ex: we can load the module on menu mouseover)

In this article lets learn about opting for a particular module to preload by using the custom property in the data property of route class.

OptInPreloading: Here we will be using a custom data attribute called preload to check any lazy-loaded module has this then will preload those modules.

opt-in-preload-strategy.service.ts

import { Injectable } from "@angular/core";
import { PreloadingStrategy, Route } from "@angular/router";
import { Observable, EMPTY } from "rxjs";

@Injectable({
  providedIn: "root",
})
export class OptInPreloadStrategyService implements PreloadingStrategy {
  constructor() {}
  preload(
    route: Route,
    load: () => import("rxjs").Observable<any>
  ): Observable<any> {
    return route.data.preload ? load() : EMPTY;
  }
}
Enter fullscreen mode Exit fullscreen mode

app-routing.module.ts

import { Routes, RouterModule } from "@angular/router";
import { OptInPreloadStrategyService } from "./stategies/opt-in-preload-strategy.service";
const routes: Routes = [
  {
    path: "dashboard",
    loadChildren: () =>
      import("./dashboard/dashboard.module").then((m) => m.DashboardModule),
  },
  {
    path: "employee",
    loadChildren: () =>
      import("./employee/employee.module").then((m) => m.EmployeeModule),
    data: { preload: true },
  },
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      preloadingStrategy: OptInPreloadStrategyService,
    }),
  ],
  exports: [RouterModule],
})
export class AppRoutingModule {}
Enter fullscreen mode Exit fullscreen mode

In the above code snippet, we see the second parameter for the RouterModule to use the preloading strategy to use the custom preload strategy service.

Top comments (0)