Skip to content

Instantly share code, notes, and snippets.

@NetanelBasal
Created August 25, 2020 06:38
Show Gist options
  • Save NetanelBasal/7c37b0542331f22c7c6b74391b23a308 to your computer and use it in GitHub Desktop.
Save NetanelBasal/7c37b0542331f22c7c6b74391b23a308 to your computer and use it in GitHub Desktop.
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');
}
}
}
@ravivit9
Copy link

Hi, how to use the lazy loading directive in html

@deveras
Copy link

deveras commented Dec 7, 2020

@ravivit9 the directive will do the work for you if you have it declared in your app.module.ts
@NetanelBasal Loved the idea, but I believe renderer2 usage is preferred

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

@Directive(
  { selector: 'img' }
)
export class LazyImageLoadingDirective
{
  constructor(private renderer:Renderer2, private element:ElementRef<HTMLImageElement>) {
    if ("loading" in HTMLImageElement.prototype) {
      this.renderer.setAttribute(this.element.nativeElement, "loading", "lazy");
    }
  }

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment