Created
April 25, 2020 11:57
-
-
Save m3g4p0p/68483fec45411f21c4ac08980dedae6f to your computer and use it in GitHub Desktop.
polyfill for the loading="lazy" image attribute
This file contains hidden or 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
/** | |
* 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