Angular

Image lazy loading defers the loading of an image that isn’t currently visible in the viewport. Such an image will be loaded only when the user scrolls and the image becomes visible. Using this technique, we can gain better performance and load time.

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"> 

The loading attribute supports three options — autoeager, and lazy. Setting it to lazy will defer the loading of the resource until it reaches a calculated distance from the viewport.

Lazy load image frames

Let’s create a directive that seamlessly adds this attribute if the browser supports it:

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');
    }
  }
}

We check if the browser supports this feature. If that’s the case, we add the loading attribute; Otherwise, we leave the default behavior.

We can also take it one step further and fallback to an IntersectionObserver implementation, which is supported by all browsers (except IE).

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
    }
  }
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here