@defer and Performance
@defer loads part of a template - and the code behind it - only when it's needed. Heavy parts such as charts, maps, comments or video players no longer slow down the first load.
The faster an app opens, the more people stay - especially on mobile networks. Much of a page isn't visible at first (comments below the fold, a chart in a tab, a map), so there's no need to download its code immediately. @defer turns "load it later" into a simple template block, and Angular takes care of splitting the code.
Example
@defer (on viewport) {
<app-reviews [productId]="id()" />
} @placeholder {
<p>Reviews</p>
} @loading (minimum 300ms) {
<p>Loading reviews...</p>
} @error {
<p>Could not load reviews.</p>
}When to load
on viewport- when the block scrolls into viewon interaction- when the user clicks or focuses the placeholderon idle- when the browser is free (the default)on timer(2s)- after a delaywhen condition()- when a signal or expression becomes trueprefetch on idle- download early, show later
Other speed habits
- Use signals and
changeDetection: ChangeDetectionStrategy.OnPushso Angular checks only the components whose data changed. - Always give
@fora goodtrack(an id). - Lazy-load routes with
loadComponent. - Use
NgOptimizedImage(<img ngSrc>) for images: it sets sizes, lazy loading and priority for you. - Check your bundle size:
ng buildprints it, and warns when it grows too big.
Example
import { NgOptimizedImage } from '@angular/common';
@Component({
imports: [NgOptimizedImage],
template: `<img ngSrc="/hero.jpg" width="1200" height="600" priority alt="Big sale banner">`,
})
export class Hero {}Components inside
@defer must be standalone and not used anywhere else outside a defer block in that template - otherwise their code is already loaded and nothing is saved.Key points
- @defer loads parts of a template only when needed.
- Triggers: on viewport, on interaction, on idle, on timer.
- Use signals and OnPush to limit change detection.
📝 Test yourself
1. What does @defer (on viewport) do?
2. Which block shows before loading starts?
3. Fill in the trigger that loads a block when the user clicks it:
@defer (on ) { <app-chat /> }
