Skip to content

Instantly share code, notes, and snippets.

@m3g4p0p
Created April 25, 2020 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m3g4p0p/68483fec45411f21c4ac08980dedae6f to your computer and use it in GitHub Desktop.
Save m3g4p0p/68483fec45411f21c4ac08980dedae6f to your computer and use it in GitHub Desktop.
polyfill for the loading="lazy" image attribute
/**
* Simple polyfill for the loading="lazy" image attribute
* based on gandalf458's idea @ https://tinyurl.com/ya2wlg93
*/
document.addEventListener('DOMContentLoaded', function () {
if ('loading' in HTMLImageElement.prototype) {
return
}
var images = Array.prototype.map.call(
document.querySelectorAll('[loading="lazy"]'),
function (image) {
image.dataset.src = image.src
image.removeAttribute('src')
return image
}
)
var checkImage = function (image, index) {
if (
image.getBoundingClientRect().top <
window.scrollY + window.innerHeight
) {
image.src = image.dataset.src
delete image.dataset.src
}
return !image.src
}
var updateImages = function () {
images = images.filter(checkImage)
if (!images.length) {
window.removeEventListener('scroll', updateImages)
}
}
window.addEventListener('scroll', updateImages)
updateImages()
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment