'delay modules preload after first app rendering

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



Solution 1:[1]

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
});

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chris Fremgen
Solution 2 Stepan Suvorov