Angular - Lazy load images in simple way

Angular - Lazy load images in simple way
Lazy load images in simple way using Angular - mobilelabs.in

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.

loading attribute support for the browsers
Created by - mobilelabs.in

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 🚀

Angular 9 - Lazy load components using ivy compiler
Recently Angular 9 was officially released with new ivy compiler. Lets dive into how to lazy load your component using angular 9 latest update on ivy compiler for better perfomance.
How to increase Angular performance like a pro - part 1
Large angular application user has to wait until all the dependant javascript assets loads in the browser this will be big problem when the application scales.
How to increase Angular performance like a pro - part 2
Latest Angular release is power packed with so much of features like PWA, Performance, Testing, Animation, Server Side Rendering and etc.