Sub topic 11
Avoiding layout shift and choosing what to defer
This chapter assumes you can write a standalone component, know the @defer syntax with @placeholder, @loading and @error, and have seen the basic triggers. It covers two decisions: how to make a deferred block appear without moving the page, and which parts of a page are worth deferring at all.
What layout shift is and how @defer causes it
Layout shift happens when content already on screen moves because something above or beside it changed size. Browsers measure this as Cumulative Layout Shift (CLS), one of the Core Web Vitals. A high CLS score means the page jumped while the user was reading or about to click.
A @defer block creates a swap. Angular first renders the @placeholder content. When the trigger fires and the chunk loads, Angular removes the placeholder, optionally shows @loading content, and finally renders the main content. Each swap can change the height of that region. Everything below the region moves with it.
sequenceDiagramWait, that is not valid in this chapter's format, so the swap is shown as a state diagram instead.
Every arrow in this diagram is a possible size change. Your job is to make the placeholder, loading and complete states occupy the same space, or to defer only content where a change cannot be seen.
Reserve space for the deferred content
The most reliable fix is a fixed or minimum size on a wrapper that exists in every state. The placeholder holds the space, the loading block holds the same space, and the real content fills it.
import { Component, input } from '@angular/core';
import { ReviewsComponent } from './reviews.component';
import { SpinnerComponent } from './spinner.component';
@Component({
selector: 'app-product-reviews',
imports: [ReviewsComponent, SpinnerComponent],
template: `
@defer (on viewport) {
<app-reviews [productId]="productId()" />
} @placeholder {
<div class="reviews-slot"></div>
} @loading (after 100ms; minimum 500ms) {
<div class="reviews-slot">
<app-spinner />
</div>
} @error {
<div class="reviews-slot">Reviews could not be loaded.</div>
}
`,
styles: `
.reviews-slot {
min-height: 480px;
}
`,
})
export class ProductReviewsComponent {
productId = input.required<string>();
}The .reviews-slot class has the same min-height in the placeholder, loading and error states. The real app-reviews component should reserve the same minimum height in its own styles, for example on its host element, so the final swap does not shrink or grow the region.
Some practical ways to pick the size:
- Use a fixed
heightormin-heightwhen you know the content size, such as a chart or a map. - Use
aspect-ratiofor media, for exampleaspect-ratio: 16 / 9on a video wrapper. - Use a skeleton (grey boxes shaped like the content) when the height depends on the data. It does not remove the shift, but it keeps it small.
- Set
widthandheightattributes on images so the browser reserves space before the file arrives.
If the real content is taller than your reserved space, the page still moves, only by less. Measure the real component and reserve its typical height.
The viewport trigger needs a placeholder that takes up space
on viewport watches an element. If you do not name one, Angular watches the placeholder. That has two consequences.
First, the placeholder must exist and must have a single root element. Text on its own, or two sibling elements, cannot be observed.
Second, the placeholder must have a size. An empty <div></div> has zero height. Zero-height elements near the top of the page can be considered visible immediately, which loads the chunk right away and defeats the point. Worse, a tiny placeholder followed by a large block is the classic recipe for a visible jump as you scroll.
@defer (on viewport) {
<app-map [location]="location" />
} @placeholder {
<div class="map-slot" style="height: 320px"></div>
}The same single-root-element rule applies to on interaction and on hover when you rely on the implicit placeholder trigger. If you need a placeholder with more than one element, wrap them in one container, or point the trigger at an element outside the block with a template reference, as in on viewport(anchor).
Placeholder, loading and complete should match
Three habits keep the transitions quiet.
- Give the loading block the same dimensions as the placeholder. A spinner that is 24px tall inside a 480px placeholder makes the region collapse during loading and expand again afterwards.
- Use the timing parameters from the earlier chapter to avoid flashes.
@loading (after 100ms; minimum 500ms)skips the loading block for fast loads and keeps it visible long enough to read when it does appear. - Keep the error block the same size too. A failed load should not push the footer around.
When a user has scrolled well past the region and a chunk then finishes loading, a swap above the viewport can shift what they are reading. Browsers have scroll anchoring that reduces this, but reserved space is more dependable than relying on it.
Choosing what to defer
Deferring is a trade. You remove code from the initial bundle, and you pay with a later swap, an extra network request, and a small chance of visible motion. Defer when the saved bytes are meaningful and the delay is not noticed.
| Content | Defer? | Reason |
|---|---|---|
| Hero image, headline, main navigation | No | It is above the fold and sets Largest Contentful Paint (LCP). Deferring delays the most important paint. |
| Anything visible on first load in the viewport | Usually no | The user sees a placeholder, then a swap. Angular's guidance is to avoid deferring content visible on initial load because it can raise CLS. |
| Comments, reviews, related items below the fold | Yes, `on viewport` | Few users reach them, and they often pull in large dependencies. |
| Charts, maps, rich text editors | Yes | They depend on heavy libraries and are often behind a tab or a button. |
| Modal dialogs and drawers | Yes, `on interaction` | They are not shown until the user asks for them. |
| Premium or role-specific panels | Yes, with `when` | Users without access never download the code. |
| Small components with no heavy dependencies | No | The extra chunk request costs more than the few bytes saved. |
Two rules help when you are unsure:
- Size of the dependency matters more than size of the component. A 40-line component that imports a charting library is a good candidate. A 400-line component that imports only Angular core is often not.
- Defer where the user has to act or scroll first. That gives the chunk time to arrive, and
prefetch on idleorprefetch on viewportcan hide the delay completely.
Dependencies shared with eager code
A component moves into the lazy chunk only if every use of it in that file's template is inside deferred blocks. If you also use it outside a @defer, or reference it in a viewChild query or the TypeScript, the compiler keeps it in the main bundle and the defer saves nothing. After adding a @defer, build and check that a new lazy chunk exists. Also check that the main bundle shrank.
ng build --stats-jsonCompare the initial chunk sizes in the build output before and after your change. If nothing changed, look for an eager reference.
Nested defer blocks
A deferred block can contain further @defer blocks. Each level adds a request that only begins once the parent has rendered, so a chain of three produces a waterfall. Prefer a flat structure with independent triggers. If you must nest, add prefetch triggers so inner chunks download while the outer block is still loading.
Check the result, not only the code
Do not guess about layout shift. Open the page in Chrome DevTools, run a Lighthouse audit, or use the Performance panel's Layout Shifts track with network throttling set to a slow profile. Throttling matters because on a fast connection the loading block may never appear, and you will miss the jump that slower users see. Also test with the cache disabled so each chunk really loads.
Summary of the working rules
- Reserve the same space in
@placeholder,@loading,@errorand the final content. - Give viewport placeholders a real size and a single root element.
- Leave above-the-fold content out of
@defer. - Defer heavy dependencies that sit behind a scroll, click or condition.
- Confirm in the build output that a new chunk exists, and confirm in a throttled browser run that the page does not move.
Exercise
A product page has a hero banner at the top, a specifications table below it, and a 3D model viewer (which imports a large library) near the bottom. A teammate wraps all three in @defer (on idle) with an empty <div></div> placeholder, and Lighthouse then reports worse CLS and LCP. Which blocks should stay deferred, which should not, and what must the remaining placeholder include?
Show answer
Remove @defer from the hero banner. It is above the fold, so deferring delays LCP and causes a swap on first view. The specifications table is probably small and likely visible early, so it should usually stay eager. Keep the 3D viewer deferred, ideally with on viewport and prefetch on idle, because its library is heavy and it sits below the fold. Its placeholder (and loading and error blocks) must be a single root element with a reserved size, such as a min-height or aspect-ratio matching the viewer, so the page below does not move when the viewer renders and so the viewport trigger does not fire immediately on a zero-height element.