A customer who only wants to see the menu doesn't need to download the admin page's code. But with the route list from the Angular Routing Basics lesson, the code of every page is downloaded when the app first opens.
Lazy loading changes that (lazy here means the code is loaded only when it's needed). A page's code is downloaded when that page is first opened, not when the app opens. The result is a smaller first download, and the first page shows sooner. Picture Jali setting up his cart every afternoon. He doesn't bring every ingredient from the storeroom. He brings only the ingredients for the menu items that almost everyone orders. The ingredients for the special pancake are fetched from the storeroom when someone orders one, and once fetched, they stay on the cart. The cart is the initial bundle, the JavaScript code downloaded when the app opens. The storeroom is the chunk files on the server, pieces of code split off from the initial bundle. The first order is the first visit to a route.
From component to loadComponent
The route list from the Angular Routing Basics lesson uses component, so every page goes into the initial bundle. This version is called eager (everything loads at the start). children: ADMIN_ROUTES puts the admin route list under the /admin address:
// src/app/app.routes.ts, eager version
import { Routes } from '@angular/router'
import { MenuPage } from './menu/menu'
import { OrdersPage } from './orders/orders'
import { ADMIN_ROUTES } from './admin/admin.routes'
export const routes: Routes = [
{ path: '', redirectTo: 'menu', pathMatch: 'full' },
{ path: 'menu', component: MenuPage },
{ path: 'orders', component: OrdersPage },
{ path: 'admin', children: ADMIN_ROUTES },
]
This is its lazy version. OrdersPage and ADMIN_ROUTES are no longer imported at the top of the file:
// src/app/app.routes.ts, lazy version
import { Routes } from '@angular/router'
import { MenuPage } from './menu/menu'
export const routes: Routes = [
{ path: '', redirectTo: 'menu', pathMatch: 'full' },
{ path: 'menu', component: MenuPage },
{
path: 'orders',
loadComponent: () => import('./orders/orders').then((m) => m.OrdersPage),
},
{
path: 'admin',
loadChildren: () => import('./admin/admin.routes').then((m) => m.ADMIN_ROUTES),
},
]
import('./orders/orders')is a dynamic import, a built-in JavaScript function. The difference from a plainimportat the top of a file:import()only runs when it's called. It returns a Promise holding that file's module, which is everything that file exports..then((m) => m.OrdersPage)runs after the file arrives.mis the module, andm.OrdersPageis the component class inside it.loadComponentholds a function that callsimport(), here an arrow function,() => .... The router calls that function when/ordersopens, not before.- The plain
OrdersPageimport at the top is gone. Left in place, it keeps the component in the initial bundle. - Menu stays
component, because the first page is needed when the app opens anyway.
What ng build produces
This is the ng build output (Angular 20) for the sample app of Jali's Pancake Stall, as printed. Raw size is the file's size, and Estimated transfer size is about how much is sent over the network. The eager version:
Initial chunk files | Names | Raw size | Estimated transfer size
main-DJOC73FW.js | main | 239.57 kB | 63.52 kB
polyfills-5CFQRCPP.js | polyfills | 34.59 kB | 11.33 kB
| Initial total | 274.16 kB | 74.86 kB
The lazy version. The Lazy chunk files part lists the chunks that are only downloaded when their route opens:
Initial chunk files | Names | Raw size | Estimated transfer size
chunk-KN7FB5LX.js | - | 120.30 kB | 36.09 kB
main-FV3QO47T.js | main | 83.95 kB | 21.56 kB
polyfills-5CFQRCPP.js | polyfills | 34.59 kB | 11.33 kB
chunk-3CKZ4X2Z.js | - | 5.63 kB | 1.61 kB
| Initial total | 244.47 kB | 70.59 kB
Lazy chunk files | Names | Raw size | Estimated transfer size
chunk-M4JL3FZ7.js | orders | 31.18 kB | 7.12 kB
chunk-KQMY4PR3.js | admin-routes | 614 bytes | 614 bytes
- The first download (Initial total) drops from 274.16 kB to 244.47 kB. That's the main benefit: a smaller initial bundle, so the first page shows sooner.
chunk-M4JL3FZ7.js(31.18 kB) holds OrdersPage plusReactiveFormsModule, because only that page uses a form. Code used by only one page moves along with that page.- Inside
main,import('./orders/orders')has been rewritten asimport("./chunk-M4JL3FZ7.js"). chunk-KN7FB5LX.jsandchunk-3CKZ4X2Z.jsare shared chunks: Angular code used bymainand also by the lazy chunks. That code is split off so it isn't downloaded twice.
Downloaded once, on the first visit
The lazy build was opened in Chrome. These are the JavaScript files the browser asked for at each step:
| Step | Files requested |
|---|---|
Open / (redirected to /menu) |
chunk-3CKZ4X2Z.js, chunk-KN7FB5LX.js, polyfills-5CFQRCPP.js, main-FV3QO47T.js |
| Click Orders | chunk-M4JL3FZ7.js |
| Click Menu | none |
| Click Orders again | none |
| Click Admin | chunk-KQMY4PR3.js |
The Orders chunk is downloaded once, the first time /orders opens. The router keeps the component it has loaded, so loadComponent isn't called again. While the chunk is still downloading, the old page stays. The contents of <router-outlet> only change once the chunk arrives.
loadChildren: one chunk for a group of routes
The admin route uses loadChildren. This is the admin route list file it loads:
// src/app/admin/admin.routes.ts
import { Routes } from '@angular/router'
import { AdminStock } from './admin-stock'
import { AdminReport } from './admin-report'
export const ADMIN_ROUTES: Routes = [
{ path: '', component: AdminStock },
{ path: 'report', component: AdminReport },
]
loadChildren loads a list of routes, not one component. The '' route in this list is /admin itself, and 'report' becomes /admin/report. Both live in chunk-KQMY4PR3.js, so moving to the report needs no further download.
In the Playground: no bundler
The Playground runs one file straight in the browser, with no bundler and no other files. A bundler is the tool that builds the bundle and chunks from the project's files at build time. There, a route with import('./orders/orders') fails when Orders is clicked. The page stays on Menu, and the console writes:
ERROR TypeError: Failed to resolve module specifier './orders/orders'
That's why the Lab's Playground code replaces import() with a Promise that returns the class from the same file, 600 ms later. The router treats that Promise the same as import(): the console logs the chunk download only once, on the first visit.
The exercise editor works like the Playground too, with no bundler. The import() inside the loadComponent function is never called, since nobody opens /admin, so there's no error. A plain import at the top of the file, on the other hand, fails as soon as the code runs: Failed to resolve module specifier "./admin/admin.component". Invalid relative url or base scheme isn't hierarchical. This shows the difference clearly: a plain import runs when the app loads, while import() waits to be called.
📌 Preloading and @defer
- Preloading means downloading in advance.
provideRouter(routes, withPreloading(PreloadAllModules))downloads every lazy chunk in the background, after the app shows. The first page stays fast, and the first click on Orders usually doesn't have to wait any more. @deferis lazy loading inside a template, not in routes:@defer (on viewport) { <app-reviews /> } @placeholder { <p>Loading reviews...</p> }. A standalone component used only inside@deferis split into its own chunk. Withon viewport, that chunk is downloaded when that part comes onto the screen, and the@placeholdercontent shows before that.
⚠️ A chunk that doesn't split off, or a navigation that fails
- Still importing the component at the top of a file. One plain import anywhere pulls the component into the initial bundle. In the sample app, the
orderschunk shrinks to 94 bytes, and the Initial total even rises to 275.65 kB. - Passing the class, not a function.
loadComponent: OrdersPagemakes the navigation fail:TypeError: Class constructor OrdersPage cannot be invoked without 'new'. - Forgetting
.then(...). Without.then((m) => m.OrdersPage)the router receives the whole module. That only works if the component is exported withexport default. Otherwise Angular 18 refuses withNG04014: Invalid configuration of route 'orders'. The component must be standalone. - A new deploy while an old tab is open. A deploy puts a new version of the app on the server. Chunk names change with every build. A tab opened before the deploy asks for an old chunk that's been deleted. The navigation is cancelled, and the console writes
ERROR TypeError: Failed to fetch dynamically imported module: .../chunk-M4JL3FZ7.js. - Exercise details. Write one route inside the
routesarray:path: 'admin'andloadComponent: () => import('./admin/admin.component').then(m => m.AdminComponent). The grader looks forloadComponentholding an arrow function that callsimport(directly, andpath: 'admin'on the same route.
TL;DR: Lazy loading delays downloading a page's code until its route first opens. loadComponent: () => import('./orders/orders').then((m) => m.OrdersPage) uses a dynamic import, import(), which only runs when the router calls the function. loadChildren works the same way for a group of routes. ng build splits a lazy page into its own chunk, a separate JavaScript file. In the sample, the initial bundle (downloaded when the app opens) drops from 274.16 kB to 244.47 kB. A chunk downloads once, on the first visit, and the old page stays until it arrives. Don't import a lazy component with a plain import in any file, give loadComponent a function, and don't forget .then(...).
⚡ loadComponent delays the download
Write:
{
path: 'orders',
loadComponent: () => import('./orders/orders').then((m) => m.OrdersPage),
},
Meaning: The router calls the function in loadComponent the first time /orders opens. Inside that function, import() is a dynamic import: the page's file is only downloaded when import() is called, then .then(...) takes the OrdersPage class from it. Don't write a plain OrdersPage import at the top of the file. If there is one, the component stays in the initial bundle, the code downloaded when the app opens.
In the exercise, write path: 'admin' and a loadComponent holding an arrow function (() =>) that calls import( directly, then .then(m => m.AdminComponent).
⚡ The main benefit: a smaller initial bundle
Meaning: ng build splits a page loaded with loadComponent into its own chunk, a separate JavaScript file that is only downloaded when its route opens. In the sample app, the first download drops from 274.16 kB to 244.47 kB, so the first page shows sooner. Code that only one page uses, like ReactiveFormsModule on the Orders page, moves into that page's chunk too.
⚡ Downloaded once, on the first visit
Guess first: you click Orders, then Menu, then Orders again. How many times is the Orders chunk downloaded?
Once, the first time /orders opens. The router keeps the component it has loaded, so loadComponent isn't called again.
Meaning: While the chunk is still downloading, the old page stays. The contents of <router-outlet> only change once the chunk arrives.