@silmar/ng-lazy-images

Easy lazy loading for Angular

Usage no npm install needed!

<script type="module">
  import silmarNgLazyImages from 'https://cdn.skypack.dev/@silmar/ng-lazy-images';
</script>

README

@silmar/ng-lazy-images

npm (scoped) pipeline status NPM

Library that will make your images or content lazy!

Inspired by ngx-lazy-load-images and How to use Lazy Loading to Slash Page Load Time

Uses IntersectionObserver and MutationObserver, both are not available pre IE 11 - in this case the lib will fall-back to immediate image loading.

You can use polyfills for both:

Install

npm i @silmar/ng-lazy-images
// or
yarn add @silmar/ng-lazy-images

Import the module

Default configuration

import { NgModule } from '@angular/core';
import { NgLazyImagesModule } from '@silmar/ng-lazy-images';

@NgModule({
  imports: [
    NgLazyImagesModule
  ]
})
export class AppComponent {}

Custom config

import { NgModule } from '@angular/core';
import { NgLazyImagesModule } from '@silmar/ng-lazy-images';

@NgModule({
  imports: [
    NgLazyImagesModule.forRoot({lazyClass: 'lazy-css-class'})
  ]
})
export class AppComponent {}
Config Object
interface LazyConfig {
  intersectionConfig?: IntersectionConfigInterface;
  lazyClass?: string;
  waitingClass?: string;
  loadingClass?: string;
  loadedClass?: string;
  errorClass?: string;
  idleLoadTimeout?: number;
}

interface IntersectionConfigInterface {
  root?: any | null;
  rootMargin?: string;
  threshold?: number | number[];
}

Use the lazy image directive

<!-- Image tags -->
<div class="image-list" siLazyImages>
  <img *ngFor="let imageUrl in images" [attr.data-src]="imageUrl">
</div>

<!-- Background images -->
<div class="image-list" siLazyImages>
  <div *ngFor="let imageUrl in images" [attr.data-background-src]="imageUrl"></div>
</div>

<!-- Use it with NG Thumbor -->
<si-thumbor-picture siLazyImages path="expobeds.com/expo_beds_logo.png" [x2]="true" [width]="320" [height]="200"
            [useDataSrc]="true"
            [bySize]="{'phone':100,'(max-width: 1060px)':'300x200', 'hd':400, 'fullhd': 600}"
            [set1pxOnLazy]="true"></si-thumbor-picture>

Use the lazy content directive

This is just a small wrapper around the IntersectionObserver. If you need to load the contents of div or something else only when/if this div gets visible in the viewport you can use this directive.

<!-- Image tags -->
<div class="some-class" siLazyContent (visible)="onDivVisible($event)">
  ...
</div>