BP173: Use lazy loading for images and other assets to reduce initial load time

Lazy loading is a technique that defers the loading of non-critical resources until they are needed. This can significantly reduce the initial load time of a page, especially on slower connections or devices. By loading images and other assets only when they are needed, the page can be displayed faster and the user can start interacting with it sooner.

To implement lazy loading in Angular, you can use the Intersection Observer API. This API allows you to detect when an element enters or exits the viewport, which can be used to trigger the loading of images and other assets. You can create a directive that uses the Intersection Observer API to load images lazily. For example, you can create a directive called "lazy-image" that takes the URL of the image as an input and loads the image when it enters the viewport. You can also add a placeholder image or loading spinner to indicate that the image is being loaded.

import { Directive, ElementRef, Input, OnInit } from '@angular/core';

@Directive({
  selector: '[lazy-image]'
})
export class LazyImageDirective implements OnInit {
  @Input('lazy-image') imageUrl: string;

  constructor(private elementRef: ElementRef) {}

  ngOnInit() {
    const observer = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const img = new Image();
          img.src = this.imageUrl;
          img.onload = () => {
            this.elementRef.nativeElement.src = this.imageUrl;
          };
          observer.unobserve(this.elementRef.nativeElement);
        }
      });
    });

    observer.observe(this.elementRef.nativeElement);
  }
}

In the above example, we create a directive called "lazy-image" that takes the URL of the image as an input. In the ngOnInit method, we create a new IntersectionObserver and observe the element that the directive is applied to. When the element enters the viewport, we create a new Image object and set its src to the URL of the image. When the image is loaded, we set the src of the element to the URL of the image. Finally, we unobserve the element to stop observing it.

Download Better Coder application to your phone and get unlimited access to the collection of enterprise best practices.

Get it on Google Play