Delay The Loading Of Images Until Needed – lazy-image

Category: Image , Javascript , Loading , Recommended | May 17, 2017
Author: notwaldorf
Views Total: 594
Official Page: Go to website
Last Update: May 17, 2017
License: MIT

Preview:

Delay The Loading Of Images Until Needed – lazy-image

Description:

The lazy-image library allows to load image sources on-demand (e.g. click, in view, etc).

How to use it:

Load the JavaScript file lazy-image.js in your html document.

<script src="lazy-image.js"></script>

Load the webcomponentsjs polyfills for legacy browsers.

<script src="/path/to/webcomponents-sd-ce.js"></script>

Embed your image and alternative text into the ‘lazy-image’ element.

<lazy-image src="1.jpg" alt="alt text" id="demo"></lazy-image>

Delay the loading of the image until you click on the alternate text.

demo.addEventListener('click', function() {
  if (!this.active)
    this.active = true;
});

Delay the loading of the image until it’s scrolled into view.

// Create an observer.
var observer = new IntersectionObserver(onChange, {
  threshold: [0.5]  // rootMargin: '50% 0%'
});

// That observes all the random images we've created.
els.forEach(el => observer.observe(el));

// Whenever we scroll...
function onChange(changes) {
  changes.forEach(change => {
    var el = change.target;
    if (!el.active)
      el.active = true;
    observer.unobserve(el);  // Don't care anymore.
  });
}