Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delay modules preload after first app rendering

Tags:

angular

I'm currently working on a single page app. in the main page several card are displayed. These cards may be enabled or disabled. If disabled, only the title of the card is displayed. If enabled, the title plus the content (which is lazy loaded) of the card is displayed By default all cards are displyed and disabled. According to user's dossier, some cards may be active when loading the page.

Currently, I didn't set any preloadingStrategy, thus, when loading the page, only the content of active card are loaded.

I have tried to set preloadingStrategy to preloadAllModules, it works fine, but it slow down the app start up. Actually, the content of active cards appear slower as all modules are loaded at the same time.

=> What I want is : 1. load the app 2. load the content of all active cards 3. preload all other modules that are not shown at startup

=> Some kind of delaying the preload after first rendering

=> Do you think that its possible ?

Thanks in advance for your feedback

like image 641
David ROSEY Avatar asked Apr 14 '26 05:04

David ROSEY


2 Answers

I believe it's possible, you have to make a custom preload strategy:

You can update your root router configuration like this:

@Injectable({
  providedIn: 'root'
})
export class CustomPreload implements PreloadingStrategy {
  preload(route: Route, load: () => Observable<any>): Observable<any> {
    // you implement this function somewhere, somehow
    if (isActiveCardRoute(route)) {
      // this will make it load immediately
      return load();
    } else {
      /* 
       * this will load the remaining modules after 5 seconds. You can possibly make a more
       * 'complex' logic to have it load sequentially or in bigger intervals to make sure
       * the app doesn't lag when loading
      */
      return timer(5000).pipe(
        switchMap(() => load())
      )
    }
  }
}

If somehow you need to find out before this, if a card is active or not by loading the api/logging in. You need to add this logic to the APP_INITIALIZER, or I guess you can add it to the CustomPreload as well, by injecting the appropriate services.

This CustomPreload, you can add to your RouterConfig:

RouterModule.forRoot(AppRoutes, {
  preloadingStrategy: CustomPreload
});
like image 74
Poul Kruijt Avatar answered Apr 15 '26 23:04

Poul Kruijt


I've created a short video explanation of how to create a Custom Preloading Strategy - https://www.youtube.com/watch?v=tDQc3CCvKfc where it's shown how to create a delay and make preloading optional

and here is the code - https://github.com/stevermeister/AngularPro-Screencast/tree/master/code/Season4-Router-Features/preloading

like image 27
Stepan Suvorov Avatar answered Apr 15 '26 23:04

Stepan Suvorov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!