Sub topic 1
Why defer part of a template: bundles and lazy loading
Prerequisites
Assume you know Angular standalone components, the imports array, template syntax, JavaScript bundles, and basic Angular CLI builds.
Why defer part of a template: bundles and lazy loading
A JavaScript bundle is a file containing code that the browser downloads. The initial bundle must load before Angular can display the page. Large charts, comments, editors, and admin panels can make this download slower.
Code splitting divides application code into multiple files. Angular's @defer block creates a lazy chunk for eligible template dependencies. The browser downloads that chunk later, so the initial page can become interactive sooner.
Your first `@defer` block
The smallest block uses the default on idle trigger. Angular loads the deferred content when the browser reaches an idle period.
import { Component } from '@angular/core';
import { CommentsComponent } from './comments.component';
@Component({
selector: 'app-post',
imports: [CommentsComponent],
template: `
<article>Post content</article>
@defer {
<app-comments />
}
`,
})
export class PostComponent {}Build the application with ng build --configuration production and inspect the generated output. The comments code should be in a separate lazy chunk rather than the initial bundle.
What can be deferred: standalone dependencies and eager references
Angular can defer standalone components, directives, and pipes used only inside the block. The imported dependency must not also be used elsewhere in the same eager template. If another part of the template references CommentsComponent, Angular must include it in the initial code path.
Keep the deferred area focused. Deferring a small panel helps less when the panel imports a large feature tree that the page needs immediately.
Showing state with `@placeholder`, `@loading` and `@error`
A placeholder reserves space before loading starts. The loading block appears when fetching takes longer than the after delay. The error block gives the user a recovery message when the chunk cannot load.
@defer (on viewport) {
<app-comments [postId]="postId" />
} @placeholder (minimum 500ms) {
<p>Comments load when this area is visible.</p>
} @loading (after 100ms; minimum 1s) {
<app-spinner />
} @error {
<p>Comments could not be loaded.</p>
}Use a placeholder with dimensions similar to the final content. This reduces layout shift, which occurs when visible content moves after loading.
Exercise
Which dependency belongs in the initial bundle: a comments component used only inside @defer, or a navigation component used both inside and outside it?
Show answer
The navigation component belongs in the initial bundle because it has an eager reference. The comments component can be deferred.