Sub topic 1
Why defer part of a template: bundles and lazy loading
Prerequisites
This chapter assumes you already know the following:
- Angular standalone components and the
importsarray of@Component. - Angular template syntax and built-in control flow such as
@ifand@for. - What a JavaScript bundle is, and the basic idea of lazy loading.
- How to run an Angular CLI build and read its output.
You do not need to know @defer syntax yet. The next chapter introduces your first @defer block. This chapter explains the problem that block solves.
The cost of one big bundle
When you build an Angular application, the build tool (esbuild in current CLI versions) walks the import graph from your entry point and writes JavaScript files to the output folder. Everything reachable through ordinary static import statements goes into the initial bundle. The browser must download, parse and run that code before the application becomes interactive.
A bigger initial bundle costs you in three ways:
- Download time. Mobile and slow networks feel this most.
- Parse and compile time. The browser spends CPU time on code the user may never need.
- Time to interactive. Metrics such as Largest Contentful Paint and Interaction to Next Paint tend to worsen as the main thread stays busy.
A typical offender is a heavy component that sits low on a page. Examples are a comment thread, a charting widget, a rich text editor or a map. The user may never scroll to it, yet its code ships with the first page load.
Code splitting and lazy loading
Code splitting means the build tool divides your application into several JavaScript files, called chunks. Lazy loading means the browser fetches some of those chunks later, when they are needed, instead of at startup.
Angular developers already know one form of this: route-level lazy loading.
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: 'admin',
loadComponent: () =>
import('./admin/admin.component').then((m) => m.AdminComponent),
},
];The dynamic import() call is the signal to the build tool. It creates a separate chunk for admin.component and everything only that component uses. The browser requests the chunk when the user navigates to /admin.
Route-level splitting has a limit. Its unit is a whole route. If a single page contains one heavy component, you cannot split it out with the router alone. You would have to write the dynamic import() yourself and render the component imperatively, for example with ViewContainerRef.createComponent. That works, but it is a lot of manual code for a common need.
What @defer adds
@defer is a template-level block. It marks part of a template as deferrable. Angular's compiler then does the splitting work for you:
- It finds the components, directives and pipes used only inside the block.
- It generates a dynamic
import()for them, which produces a separate chunk. - It generates runtime code that decides when to fetch that chunk and when to render the block's content.
Here is the smallest possible form:
@defer {
<app-comments />
}With no further configuration, Angular loads the code for app-comments in a separate chunk once the browser is idle. Idle is the default trigger. Later chapters cover the other triggers.
The key difference from route-level lazy loading is granularity. The split follows the template, not the URL. Any part of any component's template can be deferred, and you declare it with a block rather than with imperative code.
The diagram below shows the effect on what the browser loads.
A worked example
Consider a blog post page. The article text is the content users came for. The comments component is large because it pulls in a markdown renderer and a date library.
Without deferral, the component looks like this:
import { Component } from '@angular/core';
import { CommentsComponent } from './comments.component';
@Component({
selector: 'app-post',
imports: [CommentsComponent],
template: `
<article>...</article>
<app-comments />
`,
})
export class PostComponent {}CommentsComponent is statically imported, so it lands in the initial bundle along with its dependencies. Now wrap the usage in @defer:
import { Component } from '@angular/core';
import { CommentsComponent } from './comments.component';
@Component({
selector: 'app-post',
imports: [CommentsComponent],
template: `
<article>...</article>
@defer (on viewport) {
<app-comments />
} @placeholder {
<div class="comments-placeholder"></div>
}
`,
})
export class PostComponent {}Notice what did not change. The import statement is still at the top, and CommentsComponent is still listed in imports. You do not rewrite the file to use import(). The compiler sees that CommentsComponent is referenced only inside the @defer block and moves it into a lazy chunk on its own. The on viewport trigger tells Angular to render the block when the placeholder scrolls into view. The @placeholder block is what the user sees until then.
Confirming the split
Do not assume the split happened. Check the build output. Run a production build:
ng buildThe CLI prints a table of files. Before the change, you see a main chunk that includes the comments code. After the change, you see an extra lazy chunk, with a generated name, listed under "Lazy chunk files", and the initial total is smaller. You can also open the browser's network panel and reload the page. The comments chunk should not appear in the first requests. It should appear when the trigger fires.
If the chunk does not appear, the usual cause is an eager reference, which the next sections of the tutorial treat in detail. In short: if anything outside the @defer block uses the same component, the compiler keeps it in the initial bundle.
Trade-offs to keep in mind
Deferring is not free, and it is not always an improvement.
| Benefit | Cost |
|---|---|
| Smaller initial bundle, faster first load | An extra network request later, which adds latency when the content is needed |
| Less code parsed at startup | The user may see a placeholder before the real content |
| Code for unused features may never download | More states to design and test: placeholder, loading, error |
| Split follows the template, not the route | A late swap of content can shift the layout |
Three rules of thumb follow from this table:
- Defer content that is below the fold, hidden until interaction, or needed only for some users.
- Do not defer content that is visible at first paint. Deferring above-the-fold content can make Largest Contentful Paint worse, because the content now waits for an extra request.
- Small components gain little. A chunk has request overhead, so deferring a tiny component can cost more than it saves.
Later chapters return to layout shift and to choosing what to defer. For now, remember that @defer is a tool for moving work out of the critical path, not a default wrapper for everything.
What this chapter does not cover
This chapter explains the motivation. These topics come later in the tutorial:
- The rules for which dependencies can be deferred.
- The
@placeholder,@loadingand@errorblocks and their timing parameters. - The full list of triggers and prefetching.
- Server-side rendering behavior and testing.
Summary
- The initial bundle contains everything reachable through static imports. Its size affects download, parse and startup time.
- Code splitting divides an app into chunks. Lazy loading fetches some chunks later.
- Route-level lazy loading splits by page.
@defersplits by template region. - The compiler moves standalone dependencies used only inside a
@deferblock into a lazy chunk, with no change to yourimportsarray. - Verify the split in the build output and the network panel.
- Defer below-the-fold or conditional content. Avoid deferring content visible on first paint.
Exercise
A page component imports ChartComponent and lists it in its imports array. The template uses <app-chart /> inside a @defer block. After building, ChartComponent is still in the main bundle. Name one likely cause and one way to confirm it.
Show answer
A likely cause is an eager reference: something outside the @defer block also uses ChartComponent (for example, another place in the same template, or a different component that imports it statically), so the compiler cannot move it into a lazy chunk. To confirm, search the template and the other files that import it for other uses, and compare the ng build output for a separate lazy chunk file.
Exercise
Why is route-level lazy loading with loadComponent not enough to split out a heavy chart that sits at the bottom of an otherwise light page?
Show answer
Route-level lazy loading splits by route, so the whole page loads at once. The chart is part of that page, so it ships with it. @defer splits by template region, so the chart can load in its own chunk after the rest of the page.
Exercise
You have a hero banner that is visible as soon as the page opens, and a reviews section far below it. Which one should you wrap in @defer, and why?
Show answer
Wrap the reviews section. It is below the fold, so a delayed load rarely affects the user. Deferring the hero banner would delay content visible at first paint, which can worsen Largest Contentful Paint and make the page look unfinished.