Sub topic 8
Writing a selective preloading strategy
This chapter assumes you can define routes with the Angular Router, you know what loadChildren does, and you have used provideRouter in a standalone application. It builds on the previous chapter, where PreloadAllModules fetched every lazy chunk in the background.
Why preload selectively
PreloadAllModules is simple, but it downloads every lazy chunk once the first navigation finishes. In a large application that wastes bandwidth on routes most users never visit. This matters on metered mobile connections.
A selective strategy lets you preload only the routes that are likely to be used next, such as a reports page that most signed-in users open. All other routes stay lazy and load on first navigation.
The PreloadingStrategy contract
A preloading strategy is a class that implements the PreloadingStrategy interface. It has one method:
preload(route: Route, load: () => Observable<unknown>): Observable<unknown>The router calls preload() once for each route that has a loadChildren or loadComponent function and has not been loaded yet. You get two arguments:
routeis the route configuration, including itsdataproperty.loadis a function. Calling it starts the download and returns an observable.
The decision is simple. To preload the route, return load(). To skip it, return of(null), which is an observable that completes immediately without downloading anything.
Writing the strategy
This strategy preloads a route only when its data contains preload: true.
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'] ? load() : of(null);
}
}The optional chaining (route.data?.) matters because data is undefined on routes that do not set it. The bracket access ['preload'] is required because Route.data is typed as an index signature, and TypeScript settings such as noPropertyAccessFromIndexSignature reject dot access.
Marking routes and registering the strategy
Add the flag to the routes you want preloaded:
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 pass the class to withPreloading in the application config:
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, the reports chunk downloads in the background after the first navigation. The admin chunk downloads only when the user navigates to /admin.
Common errors
- Passing an instance instead of the class.
withPreloadingexpects the class, notnew SelectivePreloadingStrategy(). Angular creates it through dependency injection. - Putting
dataon the wrong route. The router only callspreload()for routes with a lazy loader, and it passes that route's owndata. A flag on a child route inside a lazy tree is not seen until that tree is loaded. - Returning
undefined. The method must return an observable. Returning nothing breaks the preloading stream. - Expecting preloading to bypass guards. A
canMatchguard still runs on navigation. Preloading only fetches the code, so it does not grant access to the route.
Extending the idea
The same pattern supports other rules. You can read a preloadDelay value from data and use timer(delay).pipe(mergeMap(() => load())). You can also check navigator.connection to skip preloading on slow networks. The contract stays the same: return load() to fetch, or an observable that completes to skip.
Exercise
A route has loadChildren but no data property. What does SelectivePreloadingStrategy return for it, and why does the code not throw an error?
Show answer
It returns of(null). The expression route.data?.['preload'] uses optional chaining, so when data is undefined the whole expression evaluates to undefined, which is falsy. The ternary then takes the of(null) branch, and the chunk is not downloaded until the user navigates to the route.
Exercise
You want to preload the reports chunk two seconds after the first navigation instead of immediately. Which RxJS operators would you use inside preload(), and what do you return for routes that should not preload?
Show answer
Return timer(2000).pipe(mergeMap(() => load())) for the delayed route. For routes that should not preload, return of(null) as before.