In Angular 19, the @defer directive is a game-changing feature designed to optimize performance by deferring the loading of non-essential components. This approach improves initial load times, enhances the user experience, and conserves resources—perfect for building modern, fast, and efficient web applications.
Why @defer Matters
When you use @defer, Angular waits to load certain components until they're needed, leveraging the IntersectionObserver API to detect when an element is about to enter the viewport. Unlike traditional lazy loading, @defer provides more granular control with options like
@placeholder, @loading, and @error for smoother UX.
Example: Deferred Image Loading
Here's a simple example that demonstrates how to use @defer to delay the loading of images:
<h1>Optimized Image Loading with `@defer`</h1>
@defer () {
<app-images></app-images>
}
@placeholder (minimum 500ms) {
<p>Loading Images...</p>
}
@loading (after 1s; minimum 500ms) {
<p>Still loading...</p>
}
Key Features of @defer
-
@placeholder:Displays temporary content while waiting for the deferred component to load. -
@loading:Shows feedback during the loading process, avoiding awkward visual "flickers." - Conditional Triggers: Load components based on various conditions like:
- on hover: Load when the user hovers over an element.
-
on timer: Load after a specified delay (
@defer(on timer(2s)) {}). - on interaction: Load after user interaction such as clicks or key presses.
Why It’s a Game-Changer
@defer significantly reduces the size of your initial application bundle, speeding up the first meaningful paint. It’s especially beneficial for large apps or resource-intensive components, enhancing performance on both fast and slow connections alike.
Top comments (2)
Thanks Amin!
You're welcome Maryam