Sub topic 7
Preloading lazy routes in the background
This chapter assumes you can define routes with the Angular Router, you know what loadComponent and loadChildren do, and you have run ng build. You should also be comfortable reading basic RxJS types such as Observable.
The cost lazy loading adds
Lazy loading shrinks the first download, but it moves a cost to navigation time. The first time a user opens /admin, the router must fetch the admin chunk before it can render. On a slow connection, the user sees a pause.
Preloading removes most of that pause. After the initial navigation finishes, the router fetches lazy chunks in the background. When the user later clicks a link, the chunk is already in the browser, so the route renders without a network wait.
No preloading is the default
If you configure nothing, the router preloads nothing. Chunks load only when a navigation needs them. This keeps the first visit cheap, but every first visit to a lazy route pays the network cost.
The router's preloader runs after the first navigation ends. It walks the route config and asks a strategy, for each route that has loadChildren, whether to load it now.
Preloading everything with PreloadAllModules
The simplest option is PreloadAllModules. You pass it to provideRouter through withPreloading.
import { ApplicationConfig } from '@angular/core';
import { provideRouter, withPreloading, PreloadAllModules } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes, withPreloading(PreloadAllModules)),
],
};Despite the name, this strategy applies to anything lazy loaded with loadChildren, including standalone route files, not only NgModules. Once the first navigation completes, the router fetches every lazy chunk in the background.
Preloading still downloads the code, so it uses bandwidth. In a large app, PreloadAllModules can fetch dozens of chunks the user never visits. That matters on metered mobile connections.
Choosing a strategy
| Strategy | What it does | Good fit |
|---|---|---|
| `NoPreloading` (default) | Loads chunks only on navigation | Small apps, or users on slow or metered networks |
| `PreloadAllModules` | Loads every lazy chunk after the first navigation | Small to medium apps where all areas are likely to be visited |
| Custom strategy | Your code decides per route | Large apps where a few areas are very likely to be visited |
Writing a selective strategy
A custom strategy is a class that implements PreloadingStrategy. Its preload method receives the route and a load function. Calling load() starts the download. Returning of(null) skips it.
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);
}
}
// In the route config:
// { path: 'reports', data: { preload: true }, loadChildren: () => import('./reports/reports.routes').then(m => m.REPORT_ROUTES) }
// In the app config:
// provideRouter(routes, withPreloading(SelectivePreloadingStrategy))The strategy reads a flag from the route's data. Only routes marked preload: true are fetched early. Other lazy routes load on demand. You decide which areas deserve the extra bandwidth, for example the ones most users open next.
The strategy is a regular injectable class, so you can inject other services into it. A common extension is to skip preloading when the browser reports a slow connection or a data-saver setting.
Preloading and guards
Preloading does not bypass canMatch. If a route has a canMatch guard that returns false, the router does not preload that route's chunk either. This means unauthorized users still do not download code they cannot use. A canActivate guard works differently: it runs after matching, so it does not stop the chunk from being preloaded.
Common mistakes
- Expecting preloading to speed up the first page. It runs after the first navigation, so it does not shrink the initial load.
- Using
PreloadAllModulesin a very large app without checking network cost. - Setting
data: { preload: true }but forgetting to pass the custom strategy towithPreloading. The flag is then ignored. - Marking
loadComponentroutes for preloading. Preloading followsloadChildren, so a route that uses onlyloadComponentis not preloaded by these strategies.
Exercise
Your app has ten lazy feature areas, but nearly every user opens only reports right after signing in. Which preloading approach fits, and how do you set it up?
Show answer
Use a custom strategy such as SelectivePreloadingStrategy. Add data: { preload: true } to the reports route only, and register the strategy with provideRouter(routes, withPreloading(SelectivePreloadingStrategy)). The other nine areas load on demand, so the app avoids downloading chunks most users never use.
Exercise
A route has canMatch: [authMatch] and loadChildren. The user is logged out and PreloadAllModules is enabled. Is the chunk downloaded in the background?
Show answer
No. The canMatch guard returns a redirect, so the route does not match and the router skips preloading it.