30 seconds of angular
Star
✨✨ New to Angular? Check out interactive Angular Codelab ✨✨

Router Custom Preloading

Angular allows us to control the way module preloading is handled.

There are 2 strategies provided by @angular/router: PreloadAllModules and NoPreloading. The latter enabled by default, only preloading lazy modules on demand.

We can override this behavior by providing custom preloading strategy: In the example below we preload all included modules if the connection is good.

import { Observable, of } from 'rxjs';
    
    export class CustomPreloading implements PreloadingStrategy {
      public preload(route: Route, load: () => Observable<any>): Observable<any> {
        return preloadingConnection() ? load() : of(null);
      }
    }
    
    const routing: ModuleWithProviders = RouterModule.forRoot(routes, {
      preloadingStrategy: CustomPreloading
    });
    

Note that that the example above would not be very efficient for larger apps, as it'll preload all the modules.

Links