#Using Angular 17 @defer to display img tag loading state

4 messages · Page 1 of 1 (latest)

fresh pilot
#

All you should need is something like this:

    <img [style.display]="loaded ? '': 'none'" src="https://picsum.photos/id/433/900/500.jpg" loading="lazy" (load)="loaded = true"/>
    <div *ngIf="!loaded">Placeholder...</div>

Explanations:

  • loading="lazy" tells the browser to load the image lazily, when the image is in the view port or close to enter the viewport
  • the image is initially hidden using CSS to not display it until it's loaded
  • the (load) event listener tells you when the image has been loaded, allowing you to display the image.
fresh pilot
#

Each image could be in its own component with that lazy loading logic.
I don't see how defer would change anything. defer is about loading JavaScript lazily, not images.

dreamy cliff
#

Can you provide the img tag with the option you used?

honest igloo