[Angular] Lazy Load Images in Angular
Today modern browsers added native support for lazy loading images, and we can benefit from it by adding one simple attribute to our img
element:
<img src="src.png" alt="Angular" loading="lazy">
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 } } }