Angular - Lazy load images

1.1k views 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.

1

There are 1 answers

0
Cuzy On BEST ANSWER

Well, that's weird.

I've made a sample project on stackblitz with your exact directive and it seems to work just fine. Inspecting the element with dev tools also displays the loading attribute being set to 'lazy'.

You could try to debug your directive (or log into the console) to see if the constructor of the directive is being called. If that's not the case, then you may need to further tweak your selector.

You should also check if your directive is properly declared, exported and imported since failing to do so won't throw an error (Since the directive isn't going to be instantiated).