Created
June 16, 2022 12:32
-
-
Save DanteDeRuwe/cb749131cfc332b3fb8d14beffafab88 to your computer and use it in GitHub Desktop.
Angular automatic lazy loading directive (using loading="lazy" if supported)
This file contains 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 { AfterViewInit, Directive, ElementRef } from '@angular/core'; | |
@Directive({ | |
selector: 'img', | |
}) | |
export class LazyDirective extends Directive implements AfterViewInit { | |
constructor(private elementRef: ElementRef<HTMLImageElement>) { | |
super(); | |
} | |
ngAfterViewInit(): void { | |
const img = this.elementRef.nativeElement; | |
if ('loading' in HTMLImageElement.prototype) { | |
img.setAttribute('loading', 'lazy'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment