Blog>
Snippets

Preloading Modules for Faster Offline Navigation

Show how to use the Angular router to preload modules while online to allow for seamless navigation of an offline app.
import { PreloadingStrategy, Route } from '@angular/router';
import { Observable, of } from 'rxjs';

export class CustomPreloadingStrategy implements PreloadingStrategy {
  preload(route: Route, load: () => Observable<any>): Observable<any> {
    return route.data && route.data.preload ? load() : of(null);
  }
}
Defines a custom preloading strategy that checks if a route has a data property with preload set to true. If so, it preloads the module; otherwise, it skips preloading.
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CustomPreloadingStrategy } from './custom-preloading-strategy';

const routes: Routes = [
  {
    path: 'feature',
    loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule),
    data: { preload: true }
  },
  // ... more routes
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { preloadingStrategy: CustomPreloadingStrategy })],
  exports: [RouterModule],
  providers: [CustomPreloadingStrategy]
})
export class AppRoutingModule { }
Sets up the AppRoutingModule with our custom preloading strategy. The feature module is marked to be preloaded by setting preload to true in the route's data.
import { Injectable } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';

@Injectable({
  providedIn: 'root'
})
export class AppUpdateService {
  constructor(private updates: SwUpdate) {
    updates.available.subscribe(event => {
      updates.activateUpdate().then(() => document.location.reload());
    });
  }
}
Sets up a service that subscribes to update events from Angular's service worker and triggers a reload of the app when an update is available.