Sub topic 1
Why split the bundle
Prerequisites
This chapter assumes you already know the following:
- How to write a standalone Angular component.
- How to define routes with the Angular Router.
- How TypeScript
importandexportwork. - How to run
ng buildwith the Angular CLI.
You do not need to know anything about lazy loading yet. This chapter explains the problem that lazy loading solves. Later chapters show the router syntax.
The cost of one big bundle
A bundle is a JavaScript file that a build tool produces by combining your source files and the libraries they import. When a user opens your app, the browser downloads that file, parses it, and runs it. Nothing renders until enough of that work is done.
If you put the whole application into one file, every visitor pays for every feature. A visitor who only wants the login page still downloads the admin dashboard, the reporting charts, and the settings screens. The cost has three parts:
- Download time. More bytes take longer to arrive, especially on slow mobile networks.
- Parse and compile time. The browser must turn the JavaScript into something it can run. This is CPU work, and it is slower on low-end phones.
- Execution time. Top-level code in every module runs at startup, even when its feature is never used.
The first two costs grow with the size of the file. A bundle that is twice as large is roughly twice as expensive to download and parse. Users feel this as a longer wait before the first screen appears.
What code splitting does
Code splitting means the build tool produces several smaller files, called chunks, instead of one large file. The browser loads only the chunks it needs right now. It fetches the others later, when the user does something that needs them.
Angular's build tooling splits code at one specific kind of statement: the dynamic import() expression. A normal static import at the top of a file is resolved at build time and always goes into the same bundle as the file that uses it. A dynamic import() is a function-like call that returns a promise. The build tool sees it and puts the imported file, along with the code only that file needs, into a separate chunk. The browser downloads that chunk when the call runs.
// Static import: always part of the same bundle as this file.
import { HomeComponent } from './home/home.component';
// Dynamic import: a separate chunk, fetched when this line runs.
async function loadAdmin() {
const module = await import('./admin/admin.routes');
return module.ADMIN_ROUTES;
}Lazy loading is the practice of using this mechanism so that a chunk is requested only when it is needed. In Angular, the natural place to do that is the router, because a route is a clear signal that the user wants a particular feature.
Initial and lazy chunks
Angular's build output distinguishes two groups of files.
- Initial chunks are loaded when the page first opens. They contain the framework runtime, your root component, your eagerly loaded routes, and anything they import statically.
- Lazy chunks are loaded later, on demand. They contain code reached only through a dynamic
import().
The goal of lazy loading is to move as much code as practical from the first group to the second. The initial chunks determine how quickly the first screen appears. Lazy chunks determine how quickly later navigations feel.
The following diagram shows the difference between the two approaches for an app with a home page, an admin area, and a reports area.
A worked example with numbers
Suppose an app has these parts, with sizes measured after minification and before compression:
| Part | Size |
|---|---|
| Framework and shared code | 180 kB |
| Home page | 40 kB |
| Admin area | 220 kB |
| Reports area (includes a charting library) | 310 kB |
With eager loading, the initial download is 180 + 40 + 220 + 310 = 750 kB. Every visitor receives all of it.
With lazy loading of the admin and reports areas, the initial download is 180 + 40 = 220 kB. The admin chunk of 220 kB is fetched only when someone opens /admin. The reports chunk of 310 kB is fetched only when someone opens /reports. A visitor who only uses the home page downloads about 70 percent less code.
The totals are not smaller. If a user visits every area, they download the same 750 kB. Lazy loading changes when the bytes are fetched, and it avoids fetching bytes that a given user never needs. It also adds some overhead: each extra chunk is a separate request, and a user who navigates to a lazy route waits for that request unless it was preloaded.
Why the router is the right split point
You could split code anywhere you write a dynamic import(). The router is the most common place for three reasons.
- Routes map to user intent. A URL change is a clear statement that the user wants a different part of the app. You know which code that part needs.
- Routes have natural boundaries. A feature area usually has its own components, services, and sometimes third-party libraries. Those can move together into one chunk.
- The router already loads things asynchronously. Route matching and activation can wait for a promise, so a chunk download fits into navigation without special handling.
Other split points exist. Angular's @defer blocks in templates can lazy load components inside a page, and you can call import() directly for a heavy library used in one action. This tutorial focuses on routes, because they give the largest and most predictable savings.
What belongs in the initial bundle
Not everything should be lazy. A reasonable rule for deciding:
- Keep eager: the app shell, the first screen most users see, the router configuration itself, and shared code that nearly every route uses.
- Make lazy: feature areas that only some users reach, areas behind a login, rarely visited screens, and anything that pulls in a large library.
The landing route is a common edge case. If most visitors land on the home page, loading it lazily adds a second request before anything useful appears. The browser must download the main bundle, run it, discover that the route is lazy, and then fetch the chunk. In that case, eager loading of the landing route is faster. Lazy loading helps most for routes that are not the first thing the user sees.
Trade-offs and edge cases
Lazy loading is not free. Be aware of these effects before you apply it everywhere.
- Navigation delay. The first visit to a lazy route waits for a network request. On a slow connection this is a visible pause. Preloading, covered in a later chapter, reduces it.
- Request count. Many tiny chunks mean many requests. HTTP/2 and HTTP/3 handle this well, but a chunk of a few kilobytes may cost more in overhead than it saves.
- Shared code. If two lazy areas import the same module, the build tool usually extracts it into a shared chunk so it is not duplicated. This is handled for you, but it means the lazy chunks you see in the build output may not match your feature folders one to one.
- Offline and failure cases. A chunk request can fail if the network drops or if you deploy a new version while a user still has the old page open. The old page may then ask for a chunk file that no longer exists. Handle navigation errors in production apps.
- Static imports undo the split. If any eagerly loaded file imports from a lazy feature with a normal
importstatement, the build tool must include that code in the initial bundle. A later chapter covers this pitfall.
Measuring before you split
Start with evidence. Run a production build and read the output.
ng buildThe Angular CLI prints a table of the files it produced. Initial files are listed in one group with their raw and estimated transfer sizes, and lazy chunks are listed in another. The initial total is the number to watch. If it is large and a feature area makes up much of it, that area is a good candidate for splitting.
For a visual breakdown, you can add the --stats-json flag and open the resulting file in a bundle analyzer. This shows which libraries and files take up the most space, so you can see whether a charting or editor library is the real cause. Later chapters show how to read the build output in detail.
How this chapter connects to the rest
The remaining chapters build on this idea in order. They review route configuration, then show how a dynamic import() appears in a route with loadComponent and loadChildren. After that they cover route-scoped providers, preloading, canMatch guards, the older NgModule approach, checking build output, and common pitfalls.
Check your understanding
Exercise
An app has a 200 kB shared core, a 50 kB landing page, and a 400 kB reports area. The landing page is eager and the reports area becomes lazy. How large is the initial download before and after, and what happens to the total download for a user who visits reports?
Show answer
Before, the initial download is 200 + 50 + 400 = 650 kB. After, it is 200 + 50 = 250 kB, and the 400 kB reports chunk is fetched only when the user opens the reports route. A user who visits reports still downloads 650 kB in total, so the total does not shrink for that user. The savings go to users who never open reports, and everyone gets a faster first load.
Exercise
Why does a normal static import of a lazy feature's component, placed in an eagerly loaded file, defeat lazy loading?
Show answer
A static import is resolved at build time, so the build tool must include the imported code in the same bundle as the file that imports it. If that file is part of the initial bundle, the feature code ships in the initial bundle too, even if the route also uses a dynamic import() elsewhere.
Exercise
Give one reason not to make the landing route lazy.
Show answer
When most visitors land on that route, a lazy landing route forces a second request for its chunk after the main bundle has loaded and run. The first screen then appears later than if the route were eager. Eager loading is faster for the route users see first.