Modern SEO-friendly Image Lazy Load Library – leniwiec.js

Category: Javascript , Loading | July 28, 2019
Author: tyczynski
Views Total: 91
Official Page: Go to website
Last Update: July 28, 2019
License: MIT

Preview:

Modern SEO-friendly Image Lazy Load Library – leniwiec.js

Description:

leniwiec.js is a tiny JavaScript lazy load library that supports img/picture tags and background images. Powered by the Intersection Observer API.

The library is fully SEO-friendly that detects the search engine robots loads all images immediately.

How to use it:

Install and import the leniwiec.js package as a module.

# Yarn
$ yarn add leniwiec

# NPM
$ npm install leniwiec --save
import skaler from 'leniwiec';

Or load the leniwiec.min.js library from the dist folder.

<script src="dist/leniwiec.min.js"></script>

Define the image path in the data attributes:

<img data-src="1.jpg" class="leniwiec" />
<div class="leniwiec" data-background-image="1.jpg"></div>
<picture class="leniwiec" data-src="small.jpg">
  <source media="(min-width: 1000px)" srcset="large.jpg" />
</picture>

Initialize and mount the leniwiec. Done.

const leniwiec = new Leniwiec('.leniwiec');
leniwiec.mount();

Available options to customize the leniwiec.

const leniwiec = new Leniwiec('.leniwiec', {

      // Intersection_Observer_API options
      root: null,
      rootMargin: '0px',
      threshold: 0,

      // error class
      errorClassName: 'is-error',

      // loaded class
      loadedClassName: 'is-loaded'
      
});

Use the data-load-image attribute to implement a progressive image loading effect.

<div class="js-progressive" data-load-image="./images/progressive/1-big.jpg">
  <div style="background-image:url(./images/progressive/1-small.jpg)"></div>
  <div class="js-big"></div>
</div>
const progressive = new Leniwiec('.js-progressive', {
      threshold: 0.5,
      onLoad: (target, src) => {
        target.querySelector('.js-big').style.backgroundImage = `url(${src})`;
      }
});
progressive.mount();

Callback functions which will be fired on load and error.

const leniwiec = new Leniwiec('.leniwiec', {

      onLoad: function onLoad() {},
      onError: function onError() {}

});

Load all elements immediately.

leniwiec.loadAll();

Unobserve all elements.

leniwiec.unmount();

Changelog:

v2.0.0 (07/28/2019)

  • unmount() public method
  • loadAll() public method
  • You can pass string selector, NodeList, HTMLElement, Node, HTMLElement[] or Node[] as element
  • Abandoned support for older browsers

v1.1.0 (07/21/2019)

  • Added a new attribute data-load-image

You Might Be Interested In:


Leave a Reply