I'm attempting to implement lazy loading of images using IntersectionObserver where available, and by using a polyfill otherwise (as recommended here).
+function ($, window, document, undefined) {
var lazyImages = [].slice.call(document.querySelectorAll("img.lazy"));
var lazyLoadImage = function() {
var lazyImageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
var lazyImage = entry.target;
lazyImage.src = lazyImage.dataset.src;
lazyImage.classList.remove("lazy");
lazyImageObserver.unobserve(lazyImage);
}
});
});
lazyImages.forEach(function(lazyImage) {
lazyImageObserver.observe(lazyImage);
});
};
var lazyLoadImagePolyfill = function() {
var active = false;
if (active === false) {
active = true;
setTimeout(function() {
lazyImages.forEach(function(lazyImage) {
if ((lazyImage.getBoundingClientRect().top <= window.innerHeight
&& lazyImage.getBoundingClientRect().bottom >= 0)
&& getComputedStyle(lazyImage).display !== 'none') {
console.log('lazyImage:', lazyImage);
lazyImage.src = lazyImage.dataset.src;
lazyImage.classList.remove('lazy');
lazyImages = lazyImages.filter(function(image) {
return image !== lazyImage;
});
if (lazyImages.length === 0) {
document.removeEventListener('scroll', lazyLoadImagePolyfill);
window.removeEventListener('resize', lazyLoadImagePolyfill);
window.removeEventListener('orientationchange',
lazyLoadImagePolyfill);
}
}
});
active = false;
}, 200);
}
document.addEventListener("scroll", lazyLoadImagePolyfill);
window.addEventListener("resize", lazyLoadImagePolyfill);
window.addEventListener("orientationchange", lazyLoadImagePolyfill);
};
document.addEventListener('DOMContentLoaded', function(){
if ("IntersectionObserver" in window) {
lazyLoadImage();
} else {
lazyLoadImagePolyfill();
}
});
}(jQuery, window, document)
This approach has worked correctly in all browsers I've tested, except IE. I'm getting a SCRIPT5007: Unable to get property 'src' of undefined or null reference
in the console; the line that's throwing the error is lazyImage.src = lazyImage.dataset.src;
. However, the console.log preceding that line shows the following:
lazyImage: [object HTMLImageElement]
"lazyImage:"
<img class="lazy" src="placeholder.png" data-src="real-pic.jpg"></img>
Please note: I've been asked to not make use of an external library or plugin. Any ideas why this is happening and how to correct it?