← Back to Angular, page 7

angular-0136 · Hard senior

How do you write a custom preloading strategy that loads only selected lazy routes, for example on good connections or when a route is marked as important?

A PreloadingStrategy has one method, preload(route, load), which returns the load observable to start loading now or EMPTY to skip. Use route data flags and conditions such as the network type and the Save-Data setting to choose, and enable the strategy with withPreloading.

Full answer

Lazy loading keeps the first download small. The cost is a delay when the user first opens a lazy route. Preloading downloads lazy chunks in the background after the first render, so later navigation is instant.

Built in: PreloadAllModules (loads everything) and NoPreloading (the default). Loading everything wastes data on mobile networks, and loading nothing makes navigation slow. A custom strategy chooses.

Implementation: a class that implements PreloadingStrategy:

preload(route: Route, load: () => Observable<any>): Observable<any>

Return load() to preload the route, or of(null) / EMPTY to skip it. The router calls this for each lazy route after navigation ends.

Typical rules:

  • Only routes with data: { preload: true }.
  • Skip when the user wants less data: navigator.connection?.saveData, or an effective type of 2g or slow-2g. The Network Information API is not available in all browsers, so guard for undefined.
  • Add a delay (timer(2000).pipe(mergeMap(() => load()))) so preloading does not compete with the first page's work.
  • Preload by priority or in order, with concatMap.
  • For very large apps, predict the next route from analytics, or preload on hover with routerLink and a link directive (a third party option).

Enable with provideRouter(routes, withPreloading(SelectivePreloading)). The class is created by the injector, so it can inject services.

Server rendering: preloading is a browser concern. Guard with isPlatformBrowser so the server does not try to load chunks it does not need.

Measure the result: check the Network panel for which chunks load after start, and compare time to interactive for the first navigation with and without the strategy. Do not preload admin pages that most users never open.

typescript
import { Injectable } from '@angular/core';
import { PreloadingStrategy, Route } from '@angular/router';
import { EMPTY, Observable, mergeMap, timer } from 'rxjs';

interface NetworkInfo {
  saveData?: boolean;
  effectiveType?: string;
}

export function shouldPreload(route: Route, network: NetworkInfo | undefined): boolean {
  if (route.data?.['preload'] !== true) {
    return false;
  }
  if (network?.saveData) {
    return false;
  }
  return network?.effectiveType !== '2g' && network?.effectiveType !== 'slow-2g';
}

@Injectable({ providedIn: 'root' })
export class SelectivePreloading implements PreloadingStrategy {
  preload(route: Route, load: () => Observable<unknown>): Observable<unknown> {
    const network = (navigator as Navigator & { connection?: NetworkInfo }).connection;
    if (!shouldPreload(route, network)) {
      return EMPTY;
    }
    return timer(2000).pipe(mergeMap(() => load()));
  }
}

// provideRouter(routes, withPreloading(SelectivePreloading))
// { path: 'reports', loadComponent: () => import('./reports'), data: { preload: true } }

Angular 20.3, type-checked. The strategy was not run against a real router here. The decision function is separated so it could be unit tested.

Key points

  • `PreloadingStrategy.preload(route, load)` returns `load()` to preload or `EMPTY` to skip.
  • Choose with route `data`, network conditions, and a delay.
  • Enable with `withPreloading(Strategy)`. Guard browser-only APIs.
  • Measure in the Network panel. Do not preload rarely used routes.

Common mistakes

  • Using `PreloadAllModules` on a large app and wasting mobile data.
  • Reading `navigator.connection` without checking it exists.
  • Preloading immediately and competing with the first page's work.

Follow-ups

  • How would you preload a route when the user hovers a link?
  • How does preloading interact with route guards like `canMatch`?
  • How do you measure the benefit?

Tips

  • Mention Save-Data and slow networks. It shows real-world thinking.
  • Say you add a delay.
  • Offer measurement as the way to prove value.

Evaluation rubric

  • Implements the interface correctly.
  • Uses sensible conditions and guards unsupported APIs.
  • Enables it and measures impact.