Sub topic 15
Preloading Lazy Routes
This chapter assumes you already know lazy loading with loadChildren and loadComponent, standalone bootstrapping with provideRouter, and basic RxJS operators such as switchMap.
Lazy loading makes the first page load faster because the browser only downloads a route's code when the user navigates there. The downside is a short delay on that first visit while the chunk downloads. Preloading fixes this. After the app has rendered its first page, the router downloads lazy chunks in the background, so a later navigation to them does not have to wait for the network.
How Preloading Fits into Navigation
The preloader runs after each navigation finishes. It walks the route config, finds lazy routes whose code has not loaded yet, and asks the active preloading strategy whether to fetch each one. Preloading only downloads code and registers the child routes. It does not create components and it does not run guards or resolvers. Those still run when the user actually navigates.
Built-in Strategies
You enable preloading with the withPreloading feature of provideRouter. Angular ships two strategies:
| Strategy | Behavior | Good fit |
|---|---|---|
| `NoPreloading` | Default. Chunks load only on navigation. | Very large apps, metered connections |
| `PreloadAllModules` | Every lazy route downloads after the first navigation. | Small to medium apps |
// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter, withPreloading, PreloadAllModules } from '@angular/router';
import { AppComponent } from './app.component';
import { routes } from './app.routes';
bootstrapApplication(AppComponent, {
providers: [provideRouter(routes, withPreloading(PreloadAllModules))]
});Despite its name, PreloadAllModules also preloads routes that use loadComponent.
Writing a Custom Strategy
You can choose which routes to preload by implementing PreloadingStrategy. The router calls preload once for each lazy route. To download the chunk, return load(). To skip it, return of(null).
// selective-preloading.strategy.ts
import { Injectable } from '@angular/core';
import { PreloadingStrategy, Route } from '@angular/router';
import { Observable, of, timer } from 'rxjs';
import { switchMap } from 'rxjs/operators';
@Injectable({ providedIn: 'root' })
export class SelectivePreloadingStrategy implements PreloadingStrategy {
preload(route: Route, load: () => Observable<unknown>): Observable<unknown> {
if (route.data?.['preload']) {
const delayMs: number = route.data['preloadDelay'] ?? 0;
return timer(delayMs).pipe(switchMap(() => load()));
}
return of(null);
}
}To opt routes in, mark them with data, then register the strategy:
// app.routes.ts (excerpt)
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: 'admin',
loadChildren: () => import('./admin/admin.routes').then(m => m.ADMIN_ROUTES),
data: { preload: true, preloadDelay: 2000 }
},
{
path: 'reports',
loadComponent: () => import('./reports.component').then(m => m.ReportsComponent)
}
];
// main.ts
// provideRouter(routes, withPreloading(SelectivePreloadingStrategy))In this setup the admin chunk downloads two seconds after the first navigation. The reports chunk still waits for a click.
Common Errors
- Expecting faster startup. Preloading begins after the first navigation, so it cannot shorten initial load time. Bundle size still matters.
- Preloading everything in a huge app. This wastes bandwidth on mobile users. Use a selective strategy.
- Routes with the deprecated
canLoadguard. The preloader skips them. UsecanMatchinstead. Remember that preloaded code can still be blocked by guards at navigation time, but the user's browser can still download it. - Forgetting to return an Observable. If
preloadreturnsundefined, it throws at runtime. Returnof(null)to skip a route.
Exercise
Your app uses withPreloading(PreloadAllModules), but a lazy "billing" route protected by canLoad never appears in the Network tab until the user clicks it. Why, and how do you get it preloaded while keeping it protected?
Show answer
The preloader skips routes that have a canLoad guard, because canLoad exists to stop the code from being downloaded at all. Replace canLoad with a canMatch guard (or canActivate). The chunk will then be preloaded, and the guard will still block access when the user navigates.
Exercise
In SelectivePreloadingStrategy, what happens to a route with data: { preload: true } and no preloadDelay?
Show answer
delayMs falls back to 0, so timer(0) emits right away and switchMap calls load(). The chunk preloads as soon as the router processes that route.