Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 74 ยท Quality and Performance

Deferrable Views and Image Optimization

Load Angular components lazily with @defer triggers, placeholders, loading and error blocks, prefetching, and serve faster images with NgOptimizedImage.

The fastest code is code the browser never has to download. Lazy routes already split an app by page. Deferrable views go further: with the @defer block you split inside a page and say when each piece should load: when it scrolls into view, when the browser is idle, when the user hovers, after a timer, or when a condition becomes true. Images are the other big cost on most pages, and Angular's NgOptimizedImage directive applies a set of best practices to them automatically.

This lesson continues from control flow, where you met @if and @for; @defer uses the same block syntax.

The real Angular templates and code are read-only, because the site cannot run the Angular compiler or bundler. The runnable examples are stand-ins: a small deferred-loader model with triggers, prefetching and error states in TypeScript, and a plain-JavaScript page whose sections load on viewport, interaction and timer. They show the behavior, not how Angular splits chunks.

The @defer block

Wrap part of a template in @defer. Angular moves the components, directives and pipes used only inside it into a separate JavaScript file (chunk), and downloads that chunk only when a trigger fires.

HTML
<h1>{{ post().title }}</h1>
<article [innerHTML]="post().html"></article>

@defer (on viewport) {
  <app-comments [postId]="post().id" />
} @placeholder {
  <div class="comments-skeleton">Comments</div>
}

Before the trigger, the @placeholder content is shown. When it fires, the chunk downloads, and the real content replaces the placeholder. Visitors who never scroll to the comments never pay for them.

Two rules make this work:

  • The deferred components must be standalone, and they must not be used eagerly anywhere else in the same file, for example in a non-deferred part of the template or as a type or value in the component's regular code. If something else uses a component eagerly, the bundler keeps it in the main chunk and nothing is saved. (Angular warns you in many such cases.)
  • Defer pieces that are not needed for the first view: comment sections, charts, rich editors, maps, below-the-fold content. Never defer the main content or the largest image at the top of the page (see below), since that would hurt Largest Contentful Paint.

Triggers

A trigger says when to start loading and rendering. The common ones:

Trigger Fires when
on idle The browser is idle (the default if you write no trigger)
on viewport The placeholder (or a given element) scrolls into view
on interaction The user clicks or presses a key on the placeholder (or given element)
on hover The pointer or focus reaches the placeholder (or given element)
on timer(2s) The given time has passed
on immediate Right away, but still as a separate chunk
when expression The expression becomes true (once true, it never goes back)

You can list several; the first one that fires wins. on viewport, on interaction and on hover watch the placeholder, so they need one, and it must have a single root element Angular can observe. To watch a different element, give it a template reference variable:

HTML
<button type="button" #loadButton>Show the chart</button>

@defer (on interaction(loadButton); prefetch on idle) {
  <app-sales-chart [data]="sales()" />
} @placeholder {
  <p>Chart is not loaded yet.</p>
}

when takes any boolean expression, including a signal: @defer (when isAdmin()) renders the block once the user is an admin.

Placeholder, loading and error

Three optional blocks describe the other states:

HTML
@defer (on viewport; prefetch on idle) {
  <app-map [location]="shop().location" />
} @placeholder (minimum 300ms) {
  <div class="map-box">Map</div>
} @loading (after 150ms; minimum 800ms) {
  <div class="map-box" aria-busy="true">Loading map...</div>
} @error {
  <p>The map could not be loaded. Please reload the page.</p>
}
  • @placeholder shows before the trigger. minimum keeps it visible at least that long, so it doesn't flash for an instant if the chunk is already cached.
  • @loading shows while the chunk downloads. after 150ms waits before showing the indicator (fast loads never show it) and minimum 800ms keeps it on screen long enough not to flicker.
  • @error shows if the download fails, for example on a lost connection. Always provide one for important content.

Give the placeholder and loading blocks the same size as the final content. If the real component is taller, everything below jumps when it appears, which damages the Cumulative Layout Shift metric you will meet in performance tuning.

Prefetching

The deferred content loads in two steps: download the code, then render it. prefetch separates them: it downloads at one moment and shows later, so that the chunk is ready when the user acts.

HTML
@defer (on interaction; prefetch on hover) {
  <app-checkout-form />
} @placeholder {
  <button type="button">Checkout</button>
}

Here the code starts downloading when the pointer reaches the button, and renders when it is clicked, by which time the chunk has usually arrived. prefetch accepts the same triggers (on idle, on viewport, on timer(...), when ...). A good default for important blocks is prefetch on idle.

flowchart LR
  P["@placeholder<br/>shown from the start"] -->|"trigger fires"| L["@loading<br/>chunk downloading"]
  L -->|"success"| C["Deferred content<br/>rendered"]
  L -->|"failure"| E["@error<br/>shown"]
  P -.->|"prefetch trigger<br/>(download only)"| L

A block moves from placeholder to loading to the content or the error state, and happens only once. Prefetch starts the download earlier without rendering.

A @defer block is a one-way trip: once it has loaded, it does not go back to the placeholder, even if the trigger's condition later changes.

Deferring on the server

When you use server-side rendering, the server renders the placeholder and not the deferred content (unless you use incremental hydration with @defer (hydrate on ...)). Triggers like on viewport or on interaction don't fire on the server since there is no user. Remember this when the deferred part carries content that matters for search engines: keep that content outside the @defer, or use hydration triggers.

Optimized images with NgOptimizedImage

Images are often the biggest part of a page and the most common cause of a slow LCP and a jumpy layout. NgOptimizedImage is a directive you use by replacing src with ngSrc:

TypeScript
import { Component } from '@angular/core';
import { NgOptimizedImage } from '@angular/common';

@Component({
  selector: 'app-hero',
  imports: [NgOptimizedImage],
  template: `
    <img ngSrc="/images/hero.jpg" width="1200" height="600" priority alt="Mountains at sunrise" />

    <img ngSrc="/images/avatar.jpg" width="64" height="64" alt="Author portrait" />
  `,
})
export class HeroComponent {}

What the directive does for you:

  • Lazy loads by default: images get loading="lazy", so those below the fold wait until needed.
  • priority marks the image that is likely your Largest Contentful Paint element: it is loaded eagerly with a high fetch priority, and with SSR a preload hint is added. Use it on the one or two images visible at the top, and on no others. In development, Angular warns if it detects an LCP image without priority.
  • Requires width and height (or fill), so the browser reserves space before the image arrives, preventing layout shift. With fill, the image fills a positioned parent, like object-fit backgrounds.
  • Generates a srcset when you give it a loader, so phones download a small file and large screens a big one. Add sizes to describe how wide the image displays, for example sizes="(min-width: 800px) 800px, 100vw".
  • Warns about mistakes in development, such as an image that is much larger than the space it is shown in, or one without dimensions.

To resize and convert files you need an image loader, a function that turns /images/hero.jpg and a width into a URL on an image CDN (Cloudflare, Cloudinary, ImageKit, Imgix and others have ready-made providers, for example provideCloudinaryLoader('https://res.cloudinary.com/your-name')). Without a loader the directive still adds lazy loading, priority and layout safety, but it cannot create smaller files by itself. Whatever you do, export images at sensible sizes and prefer modern formats such as WebP or AVIF.

A runnable deferred-loader model

This stand-in models a @defer block: it has triggers, a prefetch trigger, a when condition, and the states placeholder, loading, complete and error. The "chunk" is a function that counts how often it is downloaded; a shared promise makes sure it only downloads once, even when prefetch and the trigger both want it.

TypeScript Stand-in: @defer with triggers, prefetch and errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The comments chunk is downloaded once, although both the prefetch and the trigger asked for it, and the second viewport event does nothing. The chart ends in error, the state where your @error block would show. That is the same pattern as lazy routes: one in-flight promise shared by everyone who needs the code.

A runnable page with three triggers

Scroll down inside the preview. Three sections start as placeholders. The first loads when it scrolls into view, the second when you click it, and the third two seconds after the page starts. A log at the top records what happened and when.

Stand-in: viewport, interaction and timer triggers

Notice that every block starts only once, and the sections that you never trigger would never download in a real app. In real Angular the "loading" step is a chunk of JavaScript fetched over the network, and the placeholder should be sized to avoid layout jumps.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does @defer (on viewport) do?

    The viewport trigger watches the placeholder. When it enters the viewport, the chunk for the deferred components is downloaded and the content replaces the placeholder.
  2. 2. Why might a deferred component still end up in the main bundle?

    Splitting only works if the deferred dependencies are used solely inside the @defer block. Any eager reference keeps them in the main chunk.
  3. 3. What is the purpose of "prefetch on hover" in @defer (on interaction; prefetch on hover)?

    Prefetch separates downloading from rendering. The code starts arriving on hover, and the click only has to render it.
  4. 4. Which image should get the priority attribute with NgOptimizedImage?

    priority loads the image eagerly with high fetch priority. Use it for the one or two images visible at the start, and leave the rest lazy.
  5. 5. Why does NgOptimizedImage want width and height (or fill)?

    Knowing the size in advance lets the browser lay out the page before the image arrives, which prevents content from jumping.

Summary

  • @defer splits part of a template into its own chunk and loads it on a trigger: on idle (default), on viewport, on interaction, on hover, on timer(...), on immediate or when condition.
  • @placeholder, @loading (with after and minimum) and @error cover the other states; size them like the final content to avoid layout shift.
  • prefetch downloads the code early without rendering; a block only moves forward, once.
  • Deferred components must be standalone and not referenced eagerly elsewhere; do not defer the content users see first.
  • During SSR, the placeholder is rendered unless you use incremental hydration.
  • NgOptimizedImage (ngSrc) gives lazy loading, priority for the LCP image, required dimensions, srcset with a loader and development warnings.
  • The Angular templates are read-only; the loader model and the trigger page are stand-ins.

Next: Performance Tuning