Linked Questions

Popular Questions

Angular - Lazy load images

Asked by At

I'm starting on Angular and Typescript and I'm currently stumbling on a problem, so I'm looking for some guidance.

Indeed, I would like to lazy load all the images of my application. Thus, I would like to add the loading="lazy" attribute on each of my <img></img>

In order to do that, I have created a directive with the following code:

import { Directive, ElementRef } from '@angular/core';

@Directive({ selector: 'img' })
export class LazyimgDirective {
  constructor({ nativeElement }: ElementRef<HTMLImageElement>) {
    const supports = 'loading' in HTMLImageElement.prototype;

    if (supports) {
      nativeElement.setAttribute('loading', 'lazy');
    } else {
      // fallback to IntersectionObserver

But it doesn’t seem to work. Indeed, when I open the Chrome DevTools and check, my images are all loading before I scroll and doesn't have the loading="lazy" attribute

My directive is well imported, because if I change my code and my selector to display, for example, text in yellow, it works

Thank you in advance for your answers.

Related Questions