Skip to content

Instantly share code, notes, and snippets.

@DanteDeRuwe
Created June 16, 2022 12:32
Show Gist options
  • Save DanteDeRuwe/cb749131cfc332b3fb8d14beffafab88 to your computer and use it in GitHub Desktop.
Save DanteDeRuwe/cb749131cfc332b3fb8d14beffafab88 to your computer and use it in GitHub Desktop.
Angular automatic lazy loading directive (using loading="lazy" if supported)
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