Published

Snippet for LazyLoad + Spin.js

/**
 * Identify images by class. For each image, add
 * [Spin.js](http://fgnass.github.io/spin.js/) to parent, [LazyLoad](http://verlok.github.io/lazyload/) image, stop spinner
 * when image is loaded.
 */

var imgClass = "lazy";

var spinOpts = {
  // [Spin.js options](http://fgnass.github.io/spin.js/#usage)
};

var spinners = [];
var elems = document.getElementsByClassName( imgClass );
for ( var i = 0; i < elems.length; i++ ) {
  var pId = "lazy-" + ( i + 1 );
  var parent = elems[i].parentElement;
  parent.id = pId;
  spinners[pId] = new Spinner( spinOpts ).spin( parent );
}

var lazyLoad = new LazyLoad( {
  elements_selector: "." + imgClass,
  callback_load: function( element ) {
    var spinner = spinners[element.parentElement.id];
    if ( spinner ) {
      spinner.stop();
    }
  }
} );

For use with LazyLoad by Andrea Verlicchi and Spin.js by Felix Gnass. SB and I have both checked out a few different lazyloading plugins, we’re pleased with how this one works with srcset.

Since the default positioning of Spin.js centres the spinner in the element, it’s best for the image to be the only child of the parent element. The code above assumes that this is the case. If I didn’t have control over the markup or needed to individually wrap each image for any other reason, would probably implement something similar to the above w/ jQuery (see the Spin.js jQuery plugin).