Posted on January 23, 2023
Lazy loading is a technique used to improve the performance of web pages by only loading images and other resources as they are needed, rather than loading all resources at the time the page is first loaded. This can significantly reduce the amount of data that needs to be transferred, which can improve the overall loading time of the page and reduce the amount of bandwidth used. In the context of images, this means loading images only when a user scrolls to the section of the page where the image is located. This technique is particularly useful for web pages with a large number of images, such as image-heavy websites or online stores.
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 — auto, eager, and lazy. Setting it to lazy will defer the loading of the resource until it reaches a calculated distance from the viewport.
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');
}
}
}
This is an Angular directive that targets img elements and sets the loading attribute to lazy. The Directive decorator is used to create a directive class, and the selector property is used to specify the CSS selector for the elements that the directive should apply to. The constructor function takes in an **ElementRef **of type HTMLImageElement, and uses it to access the native img element. It then checks if the browser supports the loading attribute, and if it does, sets the loading attribute to lazy on the native img element. This is used for lazy loading images.
Here is a sample application in Github