Skip to content

Instantly share code, notes, and snippets.

@pinoceniccola
Last active December 7, 2019 18:15
Show Gist options
  • Save pinoceniccola/af31fe67d2237ada331928e1b36183ad to your computer and use it in GitHub Desktop.
Save pinoceniccola/af31fe67d2237ada331928e1b36183ad to your computer and use it in GitHub Desktop.
Minimal lazyload script with IE support
(function(){
var supportsPassive = false;
try {
var opts = Object.defineProperty({}, 'passive', {
get: function() {
supportsPassive = true;
}
});
window.addEventListener("testPassive", null, opts);
window.removeEventListener("testPassive", null, opts);
} catch (e) {}
window.addEventListener('scroll', lazyload, supportsPassive ? { passive: true, once:true } : false);
function lazyload(e){
supportsPassive || window.removeEventListener('scroll', lazyload, false);
var _imgs = document.querySelectorAll('img[data-src],img[data-srcset]');
for (var i=0; i<_imgs.length; i++) {
if(_imgs[i].getAttribute('data-src')) {
_imgs[i].setAttribute('src',_imgs[i].getAttribute('data-src'));
_imgs[i].removeAttribute('data-src');
}
if(_imgs[i].getAttribute('data-srcset')) {
_imgs[i].setAttribute('srcset',_imgs[i].getAttribute('data-srcset'));
_imgs[i].removeAttribute('data-srcset');
}
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment