Sub topic 8
Writing a selective preloading strategy
This chapter assumes you know how loadComponent and loadChildren create lazy chunks and how withPreloading(PreloadAllModules) is configured. It covers the case where PreloadAllModules fetches too much, and how to write a PreloadingStrategy that chooses which routes to fetch.
Why preload everything is not always right
PreloadAllModules downloads every lazy chunk in the background once the first navigation finishes. That is a good default for a small application. In a large one it has costs:
- Rarely visited areas, such as an admin console, are downloaded by every user.
- On a slow or metered connection, background downloads compete with the data requests the current page needs.
- Parsing and executing the preloaded code uses CPU on low-end devices.
A selective strategy keeps the benefit (the likely next page opens instantly) and drops the waste. The router lets you replace the policy with your own class, so the decision becomes ordinary TypeScript.
The PreloadingStrategy contract
A strategy is a class with one method:
preload(route: Route, load: () => Observable<any>): Observable<any>The router calls preload for lazy routes it has not loaded yet. Each call receives the route configuration and a load function. You have two choices:
- Return
load()to download the chunk. The returned observable completes when the download finishes. - Return
of(null)(orEMPTY) to skip the route.
Calling load() does not start the download by itself. The router subscribes to whatever you return, and the download starts at that subscription. That is why you can wrap load() in operators such as delay or switchMap and the download is postponed with them.
Three behaviors of the router matter when you design a policy:
- The router runs preloading after each
NavigationEndevent, not only the first one. A route you skipped is offered to the strategy again after the next navigation. Your strategy can therefore react to state that changes, such as a user logging in. - The router applies the strategy to nested lazy routes as well. When a lazy parent loads, the lazy routes inside it are offered to the strategy too. A flag on the parent does not carry down to its children.
- A route that the router has already loaded is not offered again.
A flag-based strategy
The simplest policy reads a flag from the route's data property. Routes you mark with preload: true are fetched, and all others wait until the user visits them.
import { Injectable } from '@angular/core';
import { PreloadingStrategy, Route } from '@angular/router';
import { Observable, of } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class SelectivePreloadingStrategy implements PreloadingStrategy {
preload(route: Route, load: () => Observable<unknown>): Observable<unknown> {
return route.data?.['preload'] === true ? load() : of(null);
}
}Mark the routes in the configuration:
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: 'reports',
data: { preload: true },
loadChildren: () =>
import('./reports/reports.routes').then(m => m.REPORT_ROUTES),
},
{
path: 'admin',
loadChildren: () =>
import('./admin/admin.routes').then(m => m.ADMIN_ROUTES),
},
];Then register the strategy. You pass the class, not an instance, so the router creates it through dependency injection. That means the strategy can use inject() in a field initializer or its constructor.
import { ApplicationConfig } from '@angular/core';
import { provideRouter, withPreloading } from '@angular/router';
import { routes } from './app.routes';
import { SelectivePreloadingStrategy } from './selective-preloading.strategy';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes, withPreloading(SelectivePreloadingStrategy)),
],
};With this setup, reports is downloaded shortly after startup and admin is downloaded only when someone navigates to it.
Deciding which routes deserve a flag
The flag is only a mechanism. The policy behind it should come from usage data. Good candidates for preloading are:
- The route most users visit after the landing page, such as a dashboard after login.
- Routes reachable from a prominent link or button on the first screen.
- Small chunks, where the download cost is trivial.
Poor candidates are role-restricted areas, rarely used settings pages, and very large chunks such as a charting or editor feature that most sessions never open.
Adding conditions: delay and connection awareness
A strategy can decide using more than the route. The next version waits a few seconds so the first page can finish its own requests, and it skips preloading when the browser reports that the user asked to save data.
import { Injectable } from '@angular/core';
import { PreloadingStrategy, Route } from '@angular/router';
import { Observable, of, timer } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
interface NetworkInformationLike {
saveData?: boolean;
effectiveType?: string;
}
function getConnection(): NetworkInformationLike | undefined {
return (navigator as Navigator & { connection?: NetworkInformationLike })
.connection;
}
@Injectable({ providedIn: 'root' })
export class NetworkAwarePreloadingStrategy implements PreloadingStrategy {
preload(route: Route, load: () => Observable<unknown>): Observable<unknown> {
if (route.data?.['preload'] !== true) {
return of(null);
}
const connection = getConnection();
const slow =
connection?.saveData === true ||
connection?.effectiveType === '2g' ||
connection?.effectiveType === 'slow-2g';
if (slow) {
return of(null);
}
const delayMs: number = route.data?.['preloadDelay'] ?? 2000;
return timer(delayMs).pipe(mergeMap(() => load()));
}
}timer(delayMs) emits once after the delay, and mergeMap then subscribes to load(). The chunk starts downloading only at that point.
The Network Information API (navigator.connection) is not in TypeScript's standard DOM typings and is not available in every browser. The code above reads it through a small interface and treats a missing value as "connection is fine", so unsupported browsers still preload. Because the check runs on each NavigationEnd, a user who moves from a slow network to a fast one gets the route preloaded after a later navigation.
Controlling timing with application state
Because skipped routes are offered again, a strategy can wait for a condition. This example holds back a route until the user is logged in. AuthService is an assumed application service with an isLoggedIn() method.
import { Injectable, inject } from '@angular/core';
import { PreloadingStrategy, Route } from '@angular/router';
import { Observable, of } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable({ providedIn: 'root' })
export class LoginAwarePreloadingStrategy implements PreloadingStrategy {
private readonly auth = inject(AuthService);
preload(route: Route, load: () => Observable<unknown>): Observable<unknown> {
const wantsAuth = route.data?.['preloadAfterLogin'] === true;
if (wantsAuth && !this.auth.isLoggedIn()) {
return of(null);
}
return route.data?.['preload'] === true || wantsAuth ? load() : of(null);
}
}The first navigation after login triggers a new round of offers, and the strategy then returns load() for the flagged routes.
Testing a strategy
A strategy is a plain class, so you can test it without the router. Pass a route and a load function that records whether it was subscribed to.
import { Observable, of } from 'rxjs';
import { SelectivePreloadingStrategy } from './selective-preloading.strategy';
describe('SelectivePreloadingStrategy', () => {
const strategy = new SelectivePreloadingStrategy();
function run(data?: Record<string, unknown>): boolean {
let loaded = false;
const load = (): Observable<unknown> =>
new Observable(subscriber => {
loaded = true;
subscriber.next('chunk');
subscriber.complete();
});
strategy.preload({ path: 'x', data }, load).subscribe();
return loaded;
}
it('loads flagged routes', () => {
expect(run({ preload: true })).toBe(true);
});
it('skips unflagged routes', () => {
expect(run()).toBe(false);
});
});The load function here marks loaded when it is subscribed to. That mirrors what the router does, and it checks the important property: returning of(null) never triggers a download.
Common mistakes
- Returning
loadinstead of calling it. The second argument is a function.return loadhas the wrong type, andreturn load()is correct. - Calling
load()and discarding the result. The download starts only when something subscribes. If you callload()for a side effect and returnof(null), nothing downloads. - Expecting one call per route. The strategy runs again after each navigation for routes that are still unloaded. Avoid side effects such as logging or analytics inside
preloadunless you guard them. - Flagging a parent but not its lazy children. Each lazy route is judged on its own
data. If a lazy parent loads but its lazy child route has no flag, the child stays unloaded. - Putting the flag in
dataof a route that also usescanLoad. The router skips preloading for routes that definecanLoad. That guard is deprecated in favor ofcanMatch, so usecanMatchand keep the preloading policy explicit. - Measuring only the main bundle. Preloading changes when chunks arrive, not what is in
main.js. Check the Network panel in browser developer tools to confirm that flagged chunks load after startup and unflagged chunks load only on navigation.
Summary of choices
| Strategy | Downloads | Use when |
|---|---|---|
| No preloading (default) | Chunk on first visit | The app is small, or bandwidth matters more than speed. |
| `PreloadAllModules` | All lazy chunks after startup | There are few chunks and they are all likely to be used. |
| Flag-based selective strategy | Only flagged routes | You know the likely next pages. |
| Conditional strategy | Flagged routes, subject to delay, network or login state | You need to protect the first page's loading or respect the user's data settings. |
Exercise
A route is configured as { path: 'billing', data: { preload: true }, loadChildren: () => import('./billing/billing.routes').then(m => m.BILLING_ROUTES) }. Your strategy is route.data?.['preload'] ? load() : of(null). A developer changes the strategy to route.data?.['preload'] ? of(null) : load() by mistake. Which routes now preload, and what would you see in the browser's Network panel after the first page loads?
Show answer
The logic is inverted. billing and any other flagged route is skipped, and every route without the flag is preloaded. After the first page loads, the Network panel would show background requests for the chunks of unflagged routes, while the billing chunk is requested only when the user navigates to it. A unit test like the one in this chapter, with one flagged and one unflagged route, would catch this.
Exercise
You want a route preloaded only after the user has logged in, and you have a canMatch guard on the same route that sends anonymous users to /login. Why is it still important that your strategy checks login state itself, and how does the router give your strategy a chance to preload after login?
Show answer
The router does not run canMatch during preloading, so the guard alone does not stop an anonymous user's browser from downloading the chunk. The strategy must check AuthService.isLoggedIn() itself and return of(null) when the user is not logged in. The router offers unloaded routes to the strategy again after every NavigationEnd, so the navigation that follows login triggers a new call to preload, and the strategy can then return load().