我正在尝试在可用的情况下使用 IntersectionObserver 实现图像的延迟加载,否则使用 polyfill(如此处推荐的那样)。
+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)
这种方法在我测试过的所有浏览器中都能正常工作,除了 IE。我SCRIPT5007: Unable to get property 'src' of undefined or null reference
在控制台中得到一个;引发错误的行是lazyImage.src = lazyImage.dataset.src;
. 但是,该行之前的 console.log 显示以下内容:
lazyImage: [object HTMLImageElement]
"lazyImage:"
<img class="lazy" src="placeholder.png" data-src="real-pic.jpg"></img>
请注意:我被要求不要使用外部库或插件。任何想法为什么会发生这种情况以及如何纠正它?