Created
August 25, 2020 06:38
-
-
Save NetanelBasal/7c37b0542331f22c7c6b74391b23a308 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 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
Hi, how to use the lazy loading directive in html