Skip to content
jshacks.dev
Frameworks

Defer loading with the defer block in Angular

Lazy load a heavy Angular component with an at-defer block and a trigger such as viewport, with placeholder and loading states in the template.

1 min read
Summarize in AI

Splitting a component into its own chunk used to need router changes or dynamic imports. The @defer block does it in the template.

src/app/product.component.tsTypeScript
import { Component } from '@angular/core';
import { ReviewsComponent } from './reviews.component';

@Component({
  selector: 'app-product',
  imports: [ReviewsComponent],
  template: `
    <h1>Product</h1>

    @defer (on viewport) {
      <app-reviews />
    } @placeholder {
      <p>Reviews appear as you scroll.</p>
    } @loading (minimum 300ms) {
      <p>Loading reviews…</p>
    } @error {
      <p>Reviews could not be loaded.</p>
    }
  `,
})
export class ProductComponent {}
Text
Reviews appear as you scroll.     (placeholder, before it is visible)
Loading reviews…                  (while the chunk downloads)
(the reviews list)                (once loaded)

The compiler moves everything the block uses into a separate bundle, and only if the component is standalone and used nowhere else outside deferred blocks. The on viewport trigger loads it when the placeholder enters the viewport. Others include on idle, on interaction and on timer, and when takes a condition. See Deferred loading.

A @placeholder is needed for the viewport trigger, since it observes that element. Do not defer content visible on first paint, as it would delay the largest element.

Share

More snippets

Frameworks

Update state from the previous value

Pass an updater function to the React state setter when the next value depends on the last one, so batched updates do not overwrite each other.

1 min read
Frameworks

Manage state with useState

Keep a changing value in a React 19 component with useState, and see why the setter schedules a re-render instead of changing the variable.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.