Sub topic 3
Selective Preloading and Verifying Lazy Routes
Assume you know Angular standalone components, route configuration, TypeScript imports, and ng build. This chapter focuses on controlling when lazy routes load and checking that they remain separate chunks.
Writing a selective preloading strategy
Angular's preloading strategy decides which lazy routes download after the first navigation. A selective strategy can inspect route metadata and preload only routes marked with 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);
}
}Configure the strategy and mark routes individually:
provideRouter(
routes,
withPreloading(SelectivePreloadingStrategy),
);
// Route example:
{
path: 'reports',
data: { preload: true },
loadChildren: () =>
import('./reports/reports.routes').then(m => m.REPORT_ROUTES),
}Reports load in the background. An unmarked route waits until navigation.
Keeping unauthorized users from downloading a chunk with `canMatch`
A canMatch guard runs before Angular matches and loads a lazy route. Return a UrlTree to redirect an unauthorized user.
export const authMatch: CanMatchFn = () => {
const auth = inject(AuthService);
const router = inject(Router);
return auth.isLoggedIn() ? true : router.parseUrl('/login');
};Apply it to the lazy route. This can prevent the admin chunk from downloading for logged-out users.
Lazy loading NgModules in older applications
NgModule-based applications use loadChildren to resolve a module class:
{
path: 'legacy',
loadChildren: () =>
import('./legacy/legacy.module').then(m => m.LegacyModule),
}The module defines child routes with RouterModule.forChild(...). Do not also register those child routes at the application's root.
Checking the build output for lazy chunks
Run a production build:
ng buildInspect the generated JavaScript files in dist/. A lazy feature should appear in a separate chunk rather than only in the initial main bundle. Browser developer tools also show the chunk request when you navigate to the route.
Pitfalls that defeat lazy loading
- Importing a lazy component or service from eagerly loaded code can pull it into the main bundle.
- Using
PreloadAllModulesremoves the network delay later, but downloads every lazy chunk soon after startup. - A guard that runs after route loading cannot prevent the chunk download. Use
canMatch. - Incorrect route paths or missing exports cause lazy imports to fail at runtime.
Exercise
Which metadata value makes the selective strategy preload a route?
Show answer
The route must contain data: { preload: true }.