Sub topic 10
Prefetching code before it is rendered
This chapter assumes you can write a @defer block with a main trigger and a @placeholder. It also assumes you know that deferred dependencies are standalone components moved into a lazy chunk. Here you will separate two things that a plain @defer does in one step: downloading the chunk and rendering it.
Loading and rendering are two steps
A deferred block does two jobs:
- Fetch the JavaScript chunk that holds the deferred dependencies.
- Render the block's content, replacing the placeholder.
The main trigger, such as on viewport or on interaction, starts both jobs. The user waits for the download after the trigger fires, and that wait is what you see as a loading state or a pause.
A prefetch trigger moves step 1 earlier. It downloads the chunk but does not render anything. The main trigger later renders the block, and if the code has already arrived, rendering is immediate.
| Trigger kind | Syntax | What it does |
|---|---|---|
| Main | `on ...` or `when ...` | Fetches (if needed) and renders the block |
| Prefetch | `prefetch on ...` or `prefetch when ...` | Only fetches the chunk |
A first example
The example below renders a chart when the user clicks a button. A prefetch trigger downloads the chart code as soon as the browser is idle.
<button type="button" #showChart>Show chart</button>
@defer (on interaction(showChart); prefetch on idle) {
<app-chart />
} @placeholder {
<p>Press the button to see the chart.</p>
}The part after the semicolon is the prefetch trigger. When the page loads, the browser eventually goes idle and Angular requests the chunk. By the time the user clicks, the chunk is usually in the browser cache or already loaded. The click then swaps the placeholder for <app-chart /> with no network wait.
Without prefetch on idle, the click would start the download. On a slow connection the user would click and see nothing change until the chunk arrived.
The available prefetch triggers
Every main trigger has a prefetch counterpart. The prefetch keyword goes in front, and the trigger keeps its normal syntax.
| Prefetch trigger | Starts downloading when |
|---|---|
| `prefetch on idle` | The browser reports idle time (uses `requestIdleCallback`) |
| `prefetch on immediate` | Right away, without waiting for idle |
| `prefetch on timer(2s)` | The given delay has passed. Units are `ms` and `s` |
| `prefetch on viewport` | The placeholder (or a referenced element) enters the viewport |
| `prefetch on interaction` | The placeholder (or a referenced element) is clicked or focused with the keyboard |
| `prefetch on hover` | The pointer enters or the element receives focus |
| `prefetch when expr` | The expression first becomes true |
The element-based triggers (viewport, interaction, hover) accept an optional template reference, as in prefetch on hover(showChart). Without a reference, the trigger watches the @placeholder content. In that case the block needs a @placeholder with exactly one root element. The same rule applies to the main triggers.
Choosing a main trigger and a prefetch trigger
The two triggers should answer different questions. The main trigger says when the user needs to see the content. The prefetch trigger says when it is cheap and likely enough to start the download.
A useful rule is that prefetch should fire earlier than the main trigger, and on a weaker signal of intent. Some common pairings:
| Main trigger | Prefetch trigger | Reasoning |
|---|---|---|
| `on interaction` | `prefetch on hover` | Hovering often comes before clicking, so the chunk starts downloading about a second earlier |
| `on viewport` | `prefetch on idle` | The code is ready long before the user scrolls to the block |
| `on interaction` | `prefetch on idle` | The chunk is downloaded in spare time and the click feels instant |
| `when cond` | `prefetch when almostReady` | A related signal starts the download before the real condition is met |
| `on timer(10s)` | `prefetch on immediate` | The download begins at once, the render is delayed deliberately |
Here is a pairing that uses hover and viewport together:
<a routerLink="/reports" #reportsLink>Reports</a>
@defer (on viewport; prefetch on hover(reportsLink)) {
<app-report-summary />
} @placeholder {
<div class="summary-placeholder">Summary</div>
}The block renders when the placeholder scrolls into view. Hovering over the link in the meantime downloads the chunk, so the code may arrive before the block is visible.
Prefetching on a condition
prefetch when takes any template expression. A signal read works well, because the template re-evaluates it when the signal changes.
import { Component, signal } from '@angular/core';
import { ReportComponent } from './report.component';
@Component({
selector: 'app-dashboard',
imports: [ReportComponent],
template: `
<button type="button" (click)="reportRequested.set(true)">
Open report
</button>
<input
type="text"
placeholder="Filter"
(focus)="userIsFiltering.set(true)"
/>
@defer (when reportRequested(); prefetch when userIsFiltering()) {
<app-report />
} @placeholder {
<p>Open the report to see the figures.</p>
}
`,
})
export class DashboardComponent {
reportRequested = signal(false);
userIsFiltering = signal(false);
}Focusing the filter field is a weak sign that the user is about to work with data, so it starts the download. Clicking the button later renders the block. If the user never clicks, the chunk was downloaded for nothing. That cost is the trade-off of any prefetch.
Like the main when trigger, prefetch when is a one-shot. The first time the expression is true it starts the download, and nothing happens if it later becomes false again.
What happens when the triggers race
You do not have to arrange for the prefetch to finish first. Angular tracks the request for each block.
Since the diagram must use the required fence, here it is in the right form:
There are three possible orderings:
- Prefetch finishes first. The main trigger renders the block immediately and skips
@loading. - The main trigger fires while the prefetch is in flight. Angular reuses the pending request. It does not start a second download, and the block shows
@loading(if present) until the chunk arrives. - The main trigger fires with no prefetch. The main trigger starts the download itself.
Prefetching therefore does not change what the user can see. It only shortens the time between trigger and content.
Prefetching does not render or run anything
A prefetch only requests and loads the chunk. Angular does not create the deferred component or run its constructor. The component's template is not instantiated, no change detection runs for it, and its inputs are not bound. Any HTTP requests the component would make on creation do not happen yet.
The block's own state is also unchanged. While only prefetching has occurred, the @placeholder is still on screen. The @loading block appears only once rendering has started and the dependencies are still not available.
A failed prefetch does not render @error by itself. The error appears when the block tries to render and the dependencies are still not loaded. If the prefetch request failed, the main trigger can still retry the load when it fires, so a failed prefetch is usually recoverable.
Costs and trade-offs
Prefetching spends bandwidth now to save time later. Decide what to prefetch with these points in mind.
- Bytes the user may never need.
prefetch on immediateon a rarely used block makes mobile users pay for it. Preferidle,hover, or a condition tied to intent. - Competition with critical resources.
prefetch on immediatecan compete with the main bundle, images and API calls on slow networks.idlewaits for spare time and is the safer default. - No help for the first visit's initial load. Prefetching shortens the delay after the page is interactive. The deferred code is still excluded from the initial bundle, so prefetching does not make that bundle larger.
- Redundant triggers. Setting both
on idleandprefetch on idleon one block gains nothing, because both fire at the same time.
Server-side rendering
Triggers, including prefetch triggers, are browser behavior. When Angular renders on the server, it renders the @placeholder and does not run the triggers. The browser starts the main and prefetch triggers after the page loads and the app starts. If you rely on prefetch on idle, the download therefore happens in the browser, after hydration begins, not during server rendering.
Verifying that prefetching works
Check your own pairing with these steps in the browser:
- Open the Network panel and filter by JS.
- Load the page and note which chunks appear without any interaction.
- For
prefetch on idle, you should see the deferred chunk shortly after load. - For
prefetch on hover, the chunk should appear only after you hover. - Trigger the main event. No new chunk request should appear, and the content should render without a loading state.
If a chunk is requested only when the main trigger fires, the prefetch trigger is not firing. Check that the element reference exists and, for implicit triggers, that the block has a valid @placeholder.
Summary
- A
prefetchtrigger downloads the chunk and never renders the block. - The prefetch syntax mirrors the main triggers:
idle,immediate,timer,viewport,interaction,hoverandwhen. - Choose a prefetch trigger that fires earlier than the main trigger, on a weaker signal of intent.
- A main trigger that fires during an in-flight prefetch reuses the same request.
- Prefetching costs bandwidth, so use it where the chance of use is high.
Exercise
A page has a button that, when clicked, renders <app-editor /> in a @defer block. Users report a short pause after clicking while the editor code downloads. Write the @defer opening line that fixes this without changing when the editor appears, and explain which trigger fires first.
Show answer
Use @defer (on interaction(openEditor); prefetch on hover(openEditor)), where openEditor is the template reference on the button (#openEditor). Hovering fires the prefetch trigger first and downloads the chunk. The click fires the main trigger later and renders the editor from the already loaded code. If the click comes before the download has finished, Angular reuses the in-flight request instead of starting another one.
Exercise
You add prefetch on immediate to ten deferred blocks on a long article page. Page load on mobile gets slower and the network panel shows ten extra chunk requests. What is the cause, and what would you change?
Show answer
prefetch on immediate starts every download at once, so the chunks compete with critical resources and cost bandwidth for blocks the user may never reach. Replace it with prefetch on idle for blocks likely to be used, and with prefetch on viewport or prefetch on hover for the rest. For rarely used blocks, remove the prefetch trigger and let the main trigger load the code.