1

I have a relative large project in Angular where I lazy load every component besides two landing pages.

But I also have a lot of blog articles in the project which gets a lot of organic traffic and when they are lazy loaded it slows down the loading time even when they are visited directly.

Is it good practice to lazy load them anyways?

The reason I ask is because the main.js tend to be too large if I don't lazy load.

Thanks!

1

1 Answer 1

1

Hi I think a better way is to preload you modules on background here an example : Create a selective strategy :

  import { Injectable } from '@angular/core';
import { PreloadingStrategy, Route } from '@angular/router';
import { loadavg } from 'os';
import { Observable, of } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class SelectiveStrategyService implements PreloadingStrategy {
  constructor() {}
  preload(route: Route, load: () => Observable<any>): Observable<any> {
    if (route.data && route.data['preload']) {
      return load();
    }
    return of(null);
  }
}

Then load only the needed module :

import { NgModule } from '@angular/core';
import {
  Routes,
  RouterModule,
  PreloadAllModules,
  PreloadingStrategy,
} from '@angular/router';
import { SelectiveStrategyService } from './selective-strategy.service';

const routes: Routes = [
  {
    path: 'administration',
    loadChildren: () =>
      import('./administration/shell/shell.module').then((m) => m.ShellModule),
    // pass preload to true on the needed module
    data: { preload: true },
  },
  {
    path: 'clients',
    loadChildren: () =>
      import('./client/client.module').then((m) => m.ClientlModule),
  },
  { path: '**', redirectTo: '/administration', pathMatch: 'full' },
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      preloadingStrategy: SelectiveStrategyService,
    }),
  ],
  exports: [RouterModule],
})
export class AppRoutingModule {}
Sign up to request clarification or add additional context in comments.

9 Comments

I experience that PreloadAllModules made it a little slow. So I made my own strategy like this: preload(route: Route, load: () => Observable<any>): Observable<any> { if (!route?.data?.preload) { return of(false); } return of(true).pipe(delay(5000), switchMap(() => load())); //return load(); }
But in your case you only lazyLoads one module. I have a large project where I have to lazy load a lot of modules due to load time of main.
This is just an example to show you the preloading strategy and is not a full angular project.
I update the example and I hope it helps . If not please provide more info on your modules maybe I can help you better.
Thank, but does this solve my problem? If I preload it, is it faster? Is there any solution to only preload it if it is a path match?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.