Using @defer in Angular 17 to implement lazy loading.
Angular 17 introduced a new @defer block that lets you
lazy-load content based on specific conditions or events.
Lazy loading is a technique that enables web apps
to load resources (such as scripts) only when they are needed.
Using @defer with a declarative trigger condition
Deferred blocks support the following declarative trigger types:
1. on interaction
2. on hover
3. on idle
4. on timer
5. on viewport
Let's create an example for all of these!
@defer on interaction
Angular renders the on interaction block when the user
interacts with its @placeholder block. An interaction can be a click,
focus, or input event, like keypress:
@defer (on
interaction) {
<span>Clicked - on interaction </span>
}
@placeholder
{
<span>Placeholder - on interaction (click
on it!) </span>
}
@error {
<span>Error</span>
}
@loading(minimum
2s) {
<span
class="red">Loading...</span>
}
@defer on hover
Angular renders the on hover block when the user hovers over
its @placeholder block:
@defer (on
hover) {
<span>Hovered - on hover </span>
}
@placeholder
{
<span>Placeholder - on hover (hover
it!)</span>
}
@error {
<span>Error</span>
}
@loading(minimum
2s) {
<span
class="red">Loading...</span>
}
@defer on idle
Angular renders the on idle block when the browser reaches an
idle state after the page has been loaded:
@defer (on
idle) {
<span>Browser has reached an idle
state</span>
}
@placeholder
{
<span>Placeholder - on idle </span>
}
@error {
<span>Error</span>
}
@loading(minimum
2s) {
<span
class="red">Loading...</span>
}
@defer on timer
The on timer block is rendered after the specified time
has elapsed:
@defer (on
timer(4s)) {
<span>Visible after 4s</span>
}
@placeholder
{
<span>Placeholder – wait to 4s </span>
}
@error {
<span>Error</span>
}
@loading(minimum
2s) {
<span
class="red">Loading...</span>
}
@defer on viewport
Angular renders the on viewport block when the placeholder
enters the browser's viewport:
@defer (on
viewport) {
<app-user-list />
}
@placeholder
{
<span>Placeholder – on
viewport</span>
}
@error {
<span>Error</span>
}
@loading(minimum
2s) {
<span
class="red">Loading...</span>
}
For more detailed examples, see the YouTube video Link:
-