Last active
December 7, 2019 18:15
-
-
Save pinoceniccola/af31fe67d2237ada331928e1b36183ad to your computer and use it in GitHub Desktop.
Minimal lazyload script with IE support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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