Angular - Lazy load images in simple way

What is Lazy load
Lazy load technique defers the loading which is not visible in the viewport. Loading content only when the viewport is visible.
This technique often used for better performance and improves the loading time of the website. We can accomplish with the help of custom library like ng-lazyload-image.
Link: https://www.npmjs.com/package/ng-lazyload-image
Recent improvements in modern browsers added native support for lazy loading images in img tag.

Supported Options
- auto
- eager
- lazy
How to use loading attribute
<img src="mobilelabs-in.png" alt="mobilelabs.in loading" loading="lazy">
lazy will wait until viewport reaches calculated distance.
<img src="mobilelabs-in.png" alt="mobilelabs.in loading" loading="eager">
eager will start loading immediately.
<img src="mobilelabs-in.png" alt="mobilelabs.in loading" loading="auto">
auto is default value for the loading attribute and let the browser decides loading mode.
How we can check the compatibility in browser and use this in reusable way.
import { Directive, ElementRef } from '@angular/core';
@Directive({ selector: 'img' })
export class LazyLoadingDirective {
constructor({ nativeElement }: ElementRef<HTMLImageElement>) {
const supports = 'loading' in HTMLImageElement.prototype;
if (supports) {
nativeElement.setAttribute('loading', 'lazy');
}
}
}
This directive will check the compatibility and automatically sets the loading attribute to lazy option if the browser supports.
🚀 In Case You Missed It 🚀


