Sub topic 7
Preloading lazy routes in the background
This chapter assumes you can already define routes with provideRouter, and that you know how loadComponent and loadChildren create separate chunks. It also assumes you can read the file list that ng build prints. Here you will see what the router does with those lazy chunks after the first page is on screen, and how to choose when they are downloaded.
The cost lazy loading introduces
Lazy loading shrinks the initial bundle, but it moves the cost to the first visit to each lazy route. When a user clicks a link to /admin for the first time, the router must:
- Request the chunk file.
- Wait for the download and parse it.
- Match the route and render the component.
On a fast connection this takes a few milliseconds. On a slow mobile connection it can be a visible pause, because the old view stays on screen until the chunk arrives.
Preloading addresses this. After the app has rendered its first page, the router downloads some or all of the remaining lazy chunks in the background. A later click then finds the chunk already in memory and navigates without a network wait.
Preloading does not change the initial bundle. The first page loads just as fast as without it, and the extra downloads start afterwards.
The default: no preloading
If you do not configure anything, the router uses NoPreloading. Each lazy chunk is fetched only when the user navigates to its route. This default is a deliberate trade-off. It favors users on metered or slow connections, because they never download code for pages they do not visit.
You can state the default explicitly, which is useful when you want the intent to be visible in code review:
import { ApplicationConfig } from '@angular/core';
import { provideRouter, withPreloading, NoPreloading } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes, withPreloading(NoPreloading)),
],
};This configuration behaves the same as provideRouter(routes) with no features.
Preloading everything with PreloadAllModules
Angular ships a second strategy, PreloadAllModules. You enable it by passing it to the withPreloading feature function of provideRouter.
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)),
],
};With this configuration, the router fetches every lazy chunk it can find in the route tree once the initial navigation has finished. The name says "modules", but it applies equally to loadChildren route arrays and to loadComponent routes in current Angular versions.
You pass the strategy through provideRouter in the application config, the same place as other router features such as withComponentInputBinding. The app.config.ts file is then passed to bootstrapApplication:
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { appConfig } from './app/app.config';
bootstrapApplication(AppComponent, appConfig).catch(err => console.error(err));When the preloader runs
The timing is what makes preloading safe for the first page. The router's preloader subscribes to router events, and it starts working when a navigation ends successfully. In practice, the sequence on first load looks like this:
Three consequences follow from this timing:
- The first page is not delayed. Preloading starts after the navigation has ended, so it does not compete with the requests that render the first view.
- It competes with the user's own activity. The background requests still use the same network connection. If the user clicks a link to a chunk that is still downloading, the router waits for that download to finish.
- It runs again after later navigations. The preloader scans the route configuration at each navigation end. Chunks that are already loaded are skipped, so the repeated scans cost little.
What gets preloaded
The preloader walks the route configuration looking for routes that have a loadChildren or loadComponent function. For each one it calls the active strategy, and the strategy decides whether to run the loader. Some details that matter in practice:
- It follows nesting. After a lazy route loads, the preloader inspects the routes inside it too. If
admin.routes.tscontains a nestedloadChildren,PreloadAllModuleswill eventually fetch that chunk as well. A single setting can therefore pull in a deep tree of chunks. - Routes guarded with
canLoadare skipped. The oldercanLoadguard exists to stop a chunk from downloading until the guard approves. The preloader respects that and does not preload such routes. canMatchis not evaluated by the preloader. The preloader reads the configuration and does not runcanMatchguards. A route protected only bycanMatchcan therefore still be preloaded for a user who would be redirected on a real navigation. Check the Network panel in your Angular version before assuming otherwise.- Already-loaded routes are cached. The router stores the result of the loader on the route. Preloading a route and then navigating to it does not download the chunk twice.
The canMatch point deserves its own warning.
Note that this is also a general point about frontend security. Anything you ship in a JavaScript chunk can be read by whoever downloads it. Guards control the user interface, and the server must control the data.
Choosing between the two built-in strategies
The right choice depends on how many lazy chunks you have, how large they are, and who your users are.
| Situation | Better choice | Reason |
|---|---|---|
| Small app, a few lazy routes, most users visit most pages | `PreloadAllModules` | Extra download is small and every later click is instant |
| Large app with many rarely used areas | `NoPreloading` or a selective strategy | Preloading everything wastes bandwidth on code most users never run |
| Users often on metered or slow connections | `NoPreloading` | Avoids downloading code the user may never need |
| One or two routes are visited by nearly everyone after login | A selective strategy | Gets the speed benefit without the bandwidth cost |
| Chunks are protected by `canLoad` | Either; those routes are skipped anyway | The preloader will not fetch them |
A reasonable decision procedure is to start with the default, measure how long users wait on the routes they use most, and add preloading only where the wait is noticeable. Writing a strategy that preloads only some routes is the subject of the next chapter.
Preloading in NgModule-based applications
Applications that still bootstrap with AppModule set the same strategy through RouterModule.forRoot:
import { NgModule } from '@angular/core';
import { RouterModule, PreloadAllModules } from '@angular/router';
import { routes } from './app.routes';
@NgModule({
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules }),
],
exports: [RouterModule],
})
export class AppRoutingModule {}The strategy objects are the same ones. Only the place where you register them differs. Use RouterModule.forRoot once in the root module. Feature modules use forChild, which does not accept a preloading strategy.
Verifying that preloading works
You can see preloading in the browser rather than trust the configuration.
- Build and serve the production output, for example with
ng buildand a static file server, because development servers can bundle differently. - Open the browser developer tools and select the Network tab. Filter by JS.
- Reload the page and watch the order of requests. The main bundle files load first. Lazy chunk requests then appear shortly afterwards, without any click.
- Click a link to a lazy route. No new chunk request should appear, because the chunk was already fetched.
Chunk file names in the Network tab should match the lazy chunk names in the ng build output. Section "Checking the build output for lazy chunks" in a later chapter covers reading that output in detail.
Common mistakes
- Enabling preloading to fix a large initial bundle. Preloading does nothing for the initial bundle. If the first load is too large, the cause is eager imports, not the preloading strategy.
- Assuming preloading removes the need for lazy routes. Preloading everything makes the total download close to the size of an eager build. You keep a fast first paint, but you pay the whole transfer cost in the background.
- Forgetting nested lazy routes. With
PreloadAllModulesa lazy parent that contains lazy children triggers fetches of those children as well. The total transfer may be larger than you expect. - Treating preloading as a security boundary. A preloaded chunk reaches users who are not authorized for it. Do not put secrets or privileged logic in a lazy chunk.
- Registering the strategy in the wrong place. In a standalone app the strategy goes in
provideRouter(routes, withPreloading(...)). PassingPreloadAllModulestoprovideRouter(routes)as a second argument that is not a router feature has no effect and will normally fail type checking.
Summary
The default NoPreloading strategy downloads each lazy chunk only on first navigation. PreloadAllModules fetches every discoverable lazy chunk after the first navigation ends, so later clicks are instant but the total download grows. The preloader follows nested lazy routes, skips canLoad-guarded routes, and does not run canMatch guards. You register a strategy with withPreloading in standalone apps or preloadingStrategy in RouterModule.forRoot. Verify the behavior in the Network tab rather than assuming it.
Exercise
An app has a lazy reports route that only a few users open, and a lazy dashboard route that nearly every user opens right after login. The team enables withPreloading(PreloadAllModules) and sees the initial page load time stay the same, but the data transferred in the first ten seconds rise. Explain both observations, and name the strategy approach that would fit this app better.
Show answer
The initial load time stays the same because the preloader starts only after the first navigation ends, so it does not delay the first render. Transferred data rises because PreloadAllModules also downloads the reports chunk (and any nested lazy chunks) in the background, even for users who never open it. A better fit is a selective custom strategy that preloads only dashboard, for example by marking that route with data: { preload: true }, so the common path is instant and the rare path is fetched on demand.
Exercise
A route is protected with canMatch: [authMatch] so that logged-out users are redirected to /login. A security reviewer notices the admin chunk appears in the Network tab for a logged-out user on the login page. What is the most likely cause, and what are two ways to address it?
Show answer
The app probably uses PreloadAllModules. The preloader reads the route configuration and does not run canMatch guards, so it downloads the chunk even though a real navigation would be redirected. You can address it by using a selective preloading strategy that skips the admin route (or by using NoPreloading), and by enforcing authorization on the server, because a chunk that has been downloaded can be read by the user.