Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
N

ng-lazyload-image

> 前端框架
Open source

A small library for lazy loading images for Angular apps with zero dependencies

751 stars0 likes2 views
WebsiteGitHub

About

A small library for lazy loading images for Angular apps with zero dependencies

ng-lazyload-image

A super small libary for lazy loading images for Angular apps with zero dependencies

Table of Contents

  • Demo
  • Prerequisites
  • Install
  • Setup
  • Usages
  • Debug
  • CSS
  • API
  • Hooks
  • Search Engine Optimization (SEO)
  • FAQ
  • Contributing

Demo

Visit this site: https://naughty-bose-ec1cfc.netlify.com

✅ Prerequisites

The browser you are targeting need to have support of WeakMap and String.prototype.includes. If you need to support an older browser (like IE) you will need to include polyfill for WeakMap and String.prototype.includes (see https://github.com/zloirock/core-js for example).

Make also sure to inclue a pollyfill for IntersectionObserver if you need to target IE and want to use IntersectionObserver: https://github.com/w3c/IntersectionObserver/tree/master/polyfill

⬇️ Install

To install the package, just run:

$ npm install ng-lazyload-image

or the following if you are using yarn

$ yarn add ng-lazyload-image

Setup

Include the library in your module (see app.module.ts):

javascript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { LazyLoadImageModule } from 'ng-lazyload-image'; // ` elements.  
There's no need to set `useSrcset` for `` elements, as `srcset` is used by default.  
A simple example for a `` tag:

```javascript
@Component({
  selector: 'image',
  template: `
    
      
      
      
    
  `,
})
class ImageComponent {
  screen_lg = '1200px';
  screen_md = '992px';
  defaultImage = 'https://www.placecage.com/1000/1000';
  image1 = 'https://images.unsplash.com/photo-1422004707501-e8dad229e17a?fm=jpg';
  image2 = 'https://images.unsplash.com/photo-1439931444800-9bcc83f804a6?fm=jpg';
  image3 = 'https://images.unsplash.com/photo-1417128281290-30a42da46277?fm=jpg';
}

Loading image path async

You can load image async or change the url on the fly, eg.

xml

…

ts
import { merge, fromEvent } from 'rxjs'

...

constructor() {
  this.scroll$ = merge(
    fromEvent(window, 'scroll'),
    fromEvent(someDivRef, 'scroll')
  );
}
xml

Ionic

If you are using Ionic and don't want to use IntersectionObserver, you may need to include your own scroll observable or change the scroll target. For instans if you want to have multiple scroll targets:

javascript
@Component({
  selector: 'page-image',
  template: `
    
      
    
  `,
})
export class AboutPage {
  lazyLoadImage = 'https://hd.unsplash.com/photo-1431400445088-1750c997c6b5';
}

In case of using ion-slides in Ionic 2+, you can include your own scroll observable as below.

javascript
@Component({
  selector: 'page-image',
  template: `
    
      
    
  `,
})
export class AboutPage {
  lazyLoadImage = 'https://hd.unsplash.com/photo-1431400445088-1750c997c6b5';
}

…

html
defaultImage (optional)

Type: string

Example: https://www.placecage.com/1000/1000

Path to default image. This image will be loaded right away.

You can also use src attribute for img tag to define default image:
``

or background-image property for non-image tags:

errorImage (optional)

Type: string

Example: https://i.imgur.com/XkU4Ajf.png

An image to be loaded if failing to load lazyLoad. Will load the default image (defaultImage) if absent.

xml
offset (optional)

Type: number

Example: 100

Default: 0

Number of px a image should be loaded before it is in view port

xml

…

ts
myCallbackFunction(event: StateChange) {
  switch (event.reason) {
    case 'setup':
      // The lib has been instantiated but we have not done anything yet.
      break;
    case 'observer-emit':
      // The image observer (intersection/scroll/custom observer) has emit a value so we
      // should check if the image is in the viewport.
      // `event.data` is the event in this case.
      break;
    case 'start-loading':
      // The image is in the viewport so the image will start loading
      break;
    case 'mount-image':
      // The image has been loaded successfully so lets put it into the DOM
      break;
    case 'loading-succeeded':
      // The image has successfully been loaded and placed into the DOM
      break;
    case 'loading-failed':
      // The image could not be loaded for some reason.
      // `event.data` is the error in this case
      break;
    case 'finally':
      // The last event before cleaning up
      break;
  }
}

Hooks

It is possible to hook into the loading process by create your own functions.

For example, let's say you want to fetch an image with some custom headers. If so, you can create a custom hook to fetch the image:

typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { LazyLoadImageModule, IntersectionObserverHooks, Attributes, LAZYLOAD_IMAGE_HOOKS } from 'ng-lazyload-image';
import { AppComponent } from './app.component';

export class LazyLoadImageHooks extends IntersectionObserverHooks {
  loadImage({ imagePath }: Attributes): Promise {
    return fetch(imagePath, {
      headers: {
        Authorization: 'Bearer ...',
      },
    })
      .then((res) => res.blob())
      .then((blob) => URL.createObjectURL(blob));
  }
}

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, LazyLoadImageModule],
  providers: [{ provide: LAZYLOAD_IMAGE_HOOKS, useClass: LazyLoadImageHooks }],
  bootstrap: [AppComponent],
})
export class MyAppModule {}

You can even use other services by inject them. Lets say you want to use Angulars https class instead of window.fetch:

typescript
import { NgModule, Injectable } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { LazyLoadImageModule, IntersectionObserverHooks, Attributes, LAZYLOAD_IMAGE_HOOKS } from 'ng-lazyload-image';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { AppComponent } from './app.component';

@Injectable()
export class LazyLoadImageHooks extends IntersectionObserverHooks {
  private http: HttpClient;

  constructor(http: HttpClient) {
    super();
    this.http = http;
  }

  loadImage({ imagePath }: Attributes): Observable {
    // Load the image through `HttpClient` and cancel the request if the user change page or the image gets removed
    return this.http.get(imagePath, { responseType: 'blob' }).pipe(map(blob => URL.createObjectURL(blob)));
  }
}

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, HttpClientModule, LazyLoadImageModule],
  providers: [{ provide: LAZYLOAD_IMAGE_HOOKS, useClass: LazyLoadImageHooks }],
  bootstrap: [AppComponent],
})
export class MyAppModule {}

The following hooks are supported:

getObservable

Should return an observable that emits a new value every time ng-lazyload-image should check if the image is in viewport. It is important that the emited event is of the same type isVisible expects.

Eg.

typescript
import { Attributes, IntersectionObserverHooks } from 'ng-lazyload-image';

class LazyLoadImageHooks extends IntersectionObserverHooks {
  getObservable(attributes: Attributes) {
    // Will emit `{ isIntersecting: true }` every second.
    // You will have to overwride `isVisible` if you want to pass another event
    return interval(1000).pipe(mapTo({ isIntersecting: true })));
  }
}

A more usefull example could be to add a debounce time so we only start loading the image if it has been in the view port for some time:

typescript
import { Attributes, IntersectionObserverHooks } from 'ng-lazyload-image';
import { debounceTime } from 'rxjs/operators';

class LazyLoadImageHooks extends IntersectionObserverHooks {
  getObservable(attributes: Attributes) {
    // Only load the image if it has been in the viewport for one second
    return super.getObservable(attributes).pipe(debounceTime(1000))
  }
}

See intersection-listener.ts for example.

See isVisible if you want to use your own event.

isVisible

Function to check if the element is vissible.

Eg.

typescript
import { Attributes, ScrollHooks } from 'ng-lazyload-image';

class LazyLoadImageHooks extends ScrollHooks {
  isVisible(event: Event | string, { element, scrollContainer, offset }: Attributes) {
    // `event` is form `getObservable`
    return isElementInViewport(element, scrollContainer, offset);
  }
}

If you want to create your own event, you can create both getObservable and isVisible by extend SharedHooks:

typescript
import { Attributes, SharedHooks } from 'ng-lazyload-image';

class LazyLoadImageHooks extends SharedHooks {

  getObservable(attributes: Attributes) {
    return interval(1000);
  }

  isVisible(event: number, attributes: Attributes) {
    // `event` is 0,1,2,3,4,5,...
    return isElementInViewport(element, scrollContainer, offset);
  }
}

loadImage

Function to load the image. It must return a path to the image (it can however be async, like the example below and/or return a observable).

typescript
import { IntersectionObserverHooks, Attributes } from 'ng-lazyload-image';

class LazyLoadImageHooks extends IntersectionObserverHooks {
  loadImage({ imagePath }: Attributes): Promise {
    return await fetch(imagePath)
      .then((res) => res.blob())
      .then((blob) => URL.createObjectURL(blob));
  }
}

If you don't want to load the image but instead let the browser load it for you, then you can just return the imagePath (We will however not know if the image can't be loaded and the error image will not be used):

typescript
class LazyLoadImageHooks extends IntersectionObserverHooks {
  loadImage({ imagePath }: Attributes) {
    return [imagePath];
  }
}

setLoadedImage

A function to set the image url to the DOM.

Eg.

typescript
import { IntersectionObserverHooks, Attributes } from 'ng-lazyload-image';

class LazyLoadImageHooks extends IntersectionObserverHooks {
  setLoadedImage({ element, imagePath }: Attributes) {
    // `imagePath` comes from `loadImage`
    element.src = imagePath;
  }
}

setErrorImage

This function will be called if the lazy image cant be loaded.

Eg.

typescript
import { IntersectionObserverHooks, Attributes } from 'ng-lazyload-image';

class LazyLoadImageHooks extends IntersectionObserverHooks {
  setErrorImage({ element, errorImagePath }: Attributes) {
    element.src = errorImagePath;
  }
}

setup

This function will be called on setup. Can be useful for (re)setting css-classes and setting the default image.

This function will be called every time an attrebute is changing.

Eg.

typescript
import { IntersectionObserverHooks, Attributes } from 'ng-lazyload-image';

class LazyLoadImageHooks extends IntersectionObserverHooks {
  setup(attributes: Attributes) {
    // Overwride the path to the default image for all lazyloaded images
    attributes.defaultImagePath = 'some/path.jpg';
    // You can always call the base `setup` if you want to keep the default behavior
    super.setup(attributes);
  }
}

finally

This function will be called on teardown. Can be useful for setting css-classes.

Eg.

typescript
import { IntersectionObserverHooks, Attributes } from 'ng-lazyload-image';

class LazyLoadImageHooks extends IntersectionObserverHooks {
  finally(attributes: Attributes) {
    // So something
  }
}

isBot

A function to check if the current user is a bot or not. Can be useful for SSR and SEO.

Default function:

typescript
import { isPlatformServer } from '@angul

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptangularlazy-loading

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category前端框架
PricingOpen source

> Related tools

R
React
用于构建用户界面的 JavaScript 库
V
Vue.js
渐进式 JavaScript 框架
N
Next.js
基于 React 的全栈 Web 框架