Sub topic 15
Preloading Lazy Routes
Lazy loading keeps the initial bundle small by downloading a route's code only when a user navigates to it. The cost is a delay on that first visit, because the browser has to fetch and parse a new chunk before the component can render. Preloading closes that gap. After the app has started, the router fetches lazy chunks in the background, so a later navigation to them feels instant.
This chapter assumes you are comfortable with loadComponent and loadChildren from the lazy loading chapter, with provideRouter, and with basic RxJS operators such as of, timer, and mergeMap.
What the Router Does by Default
Without any configuration, the router uses NoPreloading. A lazy chunk is requested only when a navigation matches its route. For many apps this is fine. On a slow mobile connection, though, the first click on a lazy section can stall for hundreds of milliseconds or more.
Preloading moves that download into idle time. The router does not preload during the first navigation. It waits until the initial navigation finishes (NavigationEnd), then walks the route configuration and asks a preloading strategy, route by route, whether to load each lazy entry.
Because the preloader recurses into loaded children, a lazy route group that itself contains lazy routes gets preloaded level by level.
Turning on PreloadAllModules
The built-in PreloadAllModules strategy loads every lazy route. You register it with the withPreloading feature of provideRouter:
// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import {
provideRouter,
withComponentInputBinding,
withPreloading,
PreloadAllModules
} from '@angular/router';
import { AppComponent } from './app.component';
import { routes } from './app.routes';
bootstrapApplication(AppComponent, {
providers: [
provideRouter(
routes,
withComponentInputBinding(),
withPreloading(PreloadAllModules)
)
]
});Despite the name, PreloadAllModules covers both loadChildren and loadComponent routes. The name dates from the NgModule era. If your app still uses RouterModule.forRoot, the equivalent is RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules }).
To confirm it works, open the browser's Network tab, load the home page, and watch the lazy chunks arrive after the main bundle settles. Then navigate to the lazy route. No new script request should appear.
Choosing a Strategy
Preloading everything spends bandwidth on code the user may never visit. The right choice depends on how many lazy routes you have, how large they are, and who your users are.
| Strategy | What it loads | Good fit | Main cost |
|---|---|---|---|
| `NoPreloading` (default) | Nothing ahead of time | Large apps with many rarely used sections | First visit to each lazy route waits on the network |
| `PreloadAllModules` | Every lazy route, recursively | Small to mid-size apps, mostly desktop users | Downloads code users may never need |
| Custom selective strategy | Routes you flag | Apps with a few hot paths | You maintain the flags |
| Custom network-aware strategy | Flagged routes, only on fast connections | Mobile-heavy audiences | Relies on a non-standard browser API |
Writing a Custom Strategy
A preloading strategy is a class that implements PreloadingStrategy. Its single method, preload, receives the route and a load function. Return load() to fetch the chunk, or return of(null) to skip it. The router subscribes to whatever observable you return.
Selective preloading with route data
The common pattern flags routes through their data property:
// selective-preloading.strategy.ts
import { Injectable } from '@angular/core';
import { PreloadingStrategy, Route } from '@angular/router';
import { Observable, of, timer } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
@Injectable({ providedIn: 'root' })
export class SelectivePreloadingStrategy implements PreloadingStrategy {
preload(route: Route, load: () => Observable<unknown>): Observable<unknown> {
if (route.data?.['preload'] !== true) {
return of(null);
}
const delayMs: number = route.data?.['preloadDelay'] ?? 0;
return timer(delayMs).pipe(mergeMap(() => load()));
}
}Mark the routes you want:
// app.routes.ts
import { Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { NotFoundComponent } from './not-found.component';
export const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent, title: 'Home' },
{
path: 'products',
loadChildren: () => import('./products/products.routes').then(m => m.PRODUCT_ROUTES),
data: { preload: true }
},
{
path: 'reports',
loadComponent: () => import('./reports/reports.component').then(m => m.ReportsComponent),
data: { preload: true, preloadDelay: 5000 }
},
{
path: 'admin',
loadChildren: () => import('./admin/admin.routes').then(m => m.ADMIN_ROUTES)
},
{ path: '**', component: NotFoundComponent }
];Then register the class: withPreloading(SelectivePreloadingStrategy). Here the product catalog loads as soon as the first navigation ends, the reports page loads five seconds later, and admin waits for an actual visit.
Network-aware preloading
Some browsers expose navigator.connection through the Network Information API. You can use it to skip preloading when the user has turned on data saving or is on a slow link. TypeScript's DOM types do not include this API, so describe the shape yourself and treat it as optional:
// network-aware-preloading.strategy.ts
import { Injectable } from '@angular/core';
import { PreloadingStrategy, Route } from '@angular/router';
import { Observable, of } from 'rxjs';
interface NetworkInformationLike {
saveData?: boolean;
effectiveType?: 'slow-2g' | '2g' | '3g' | '4g';
}
@Injectable({ providedIn: 'root' })
export class NetworkAwarePreloadingStrategy implements PreloadingStrategy {
preload(route: Route, load: () => Observable<unknown>): Observable<unknown> {
if (route.data?.['preload'] !== true || !this.hasGoodConnection()) {
return of(null);
}
return load();
}
private hasGoodConnection(): boolean {
if (typeof navigator === 'undefined') {
return false; // server-side rendering: never preload
}
const conn = (navigator as Navigator & { connection?: NetworkInformationLike }).connection;
if (!conn) {
return true; // API unavailable (e.g. Safari, Firefox): assume a normal connection
}
if (conn.saveData) {
return false;
}
return conn.effectiveType !== 'slow-2g' && conn.effectiveType !== '2g';
}
}The strategy is a normal injectable, so it can inject() other services, such as a feature-flag service or a user-preferences store.
Gotchas and Edge Cases
canMatch does not stop preloading
The preloader does not run canMatch guards. A route protected only by canMatch will have its chunk downloaded for every user, including users who can never open it. This is harmless for security, because code shipped to the browser was never secret. It still wastes bandwidth. If you don't want admin code fetched for regular users, leave the route unflagged in a selective strategy. Alternatively, have the strategy inject your auth service and check the user's role before calling load().
The deprecated canLoad guard does block preloading. Older codebases sometimes relied on that behavior, so migrating canLoad to canMatch can quietly turn preloading on for those routes.
Preloading is not data prefetching
Preloading fetches JavaScript only. It does not create components, run guards, or execute resolvers. A resolver on a preloaded route still runs, and still blocks, at navigation time.
Errors are swallowed
If a preload request fails, for example because of a flaky network or a chunk removed by a new deployment, the router catches the error and moves on. The route will try to load again on real navigation. If you want visibility, add catchError inside your strategy and log the failure before returning of(null).
Already-loaded routes are skipped
The preloader runs after every NavigationEnd, not only the first. Routes that are already loaded are skipped, so later runs are cheap. Because of this, a strategy can make different decisions over time, for example preloading the checkout flow only after something is in the cart.
Exercises
Exercise
You enable withPreloading(PreloadAllModules), but in the Network tab the lazy chunks only appear after the home page has rendered, not alongside the main bundle. Is something misconfigured?
Show answer
No. The router starts preloading only after the initial navigation emits NavigationEnd, so lazy chunks are intentionally requested after the first view renders. This keeps preloading from competing with the initial page load.
Exercise
An app uses PreloadAllModules and protects its admin route group with canMatch: [adminGuard]. A product manager notices that regular users download the admin chunk. Explain why and give one fix.
Show answer
The preloader does not evaluate canMatch guards, so PreloadAllModules loads the admin chunk for everyone. One fix is a custom selective strategy that preloads only routes with data: { preload: true } and leaves admin unflagged. Another is a strategy that injects the auth service and calls load() for admin routes only when the user has the admin role.
Exercise
Write the preload method of a strategy that preloads a route only when route.data['preload'] is true, and logs and ignores any loading error.
Show answer
preload(route: Route, load: () => Observable<unknown>): Observable<unknown> { if (route.data?.['preload'] !== true) { return of(null); } return load().pipe(catchError(err => { console.warn('Preload failed for', route.path, err); return of(null); })); } with catchError imported from 'rxjs/operators' and of from 'rxjs'.