Lazy Loading in Angular

Lazy loading delays downloading a page's code until its route first opens. loadComponent: () => import('./orders/orders').then((m) => m.OrdersPage) uses a…

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),
  },
]

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

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

⚠️ A chunk that doesn't split off, or a navigation that fails

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.

What you will learn