我拥有一些网站,该网站是我在2019年初创建的。自那时以来,一切工作正常,但最近我意识到,Chrome浏览器中的延迟加载行为非常不稳定。在一切正常的Firefox和Edge中不存在此问题。不稳定行为是指刷新网站后是否工作。
我的js代码如下所示:
document.addEventListener("DOMContentLoaded", function () {
var lazyloadImages;
if ("IntersectionObserver" in window) {
lazyloadImages = document.querySelectorAll(".lazy-img");
alert("number of elements: " + lazyloadImages.length);
var imageObserver = new IntersectionObserver(function (entries, observer) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
var image = entry.target;
image.src = image.dataset.src;
image.classList.remove("lazy-img");
imageObserver.unobserve(image);
}
});
});
lazyloadImages.forEach(function (image) {
imageObserver.observe(image);
});
} else {
var lazyloadThrottleTimeout;
lazyloadImages = document.querySelectorAll(".lazy-img");
function lazyload() {
if (lazyloadThrottleTimeout) {
clearTimeout(lazyloadThrottleTimeout);
}
lazyloadThrottleTimeout = setTimeout(function () {
var scrollTop = window.pageYOffset;
lazyloadImages.forEach(function (img) {
if (img.offsetTop < window.innerHeight + scrollTop) {
img.src = img.dataset.src;
img.classList.remove("lazy-img");
}
});
if (lazyloadImages.length == 0) {
document.removeEventListener("scroll", lazyload);
window.removeEventListener("resize", lazyload);
window.removeEventListener("orientationChange", lazyload);
}
}, 20);
}
document.addEventListener("scroll", lazyload);
window.addEventListener("resize", lazyload);
window.addEventListener("orientationChange", lazyload);
}
});
我为测试目的添加了警报。当我按时刷新网站时,警报返回元素数量并且延迟加载工作正常,而另一时间它根本不显示警报(甚至是空列表),并且延迟加载不起作用(不显示图片) ,仅是替代文字)。这可能是什么原因?任何帮助将不胜感激。
[Deprecation] <source src> with a <picture> parent is invalid and therefore ignored. Please use <source srcset> instead
我以以下方式加载图像:
<div class="product-container"> <a href="sth.html"> <picture> <source data-srcset="images/products/sth.webp" type="image/webp" class="product-img lazy-img" alt="sth"> <source data-srcset="images/products/sth.png" type="image/png" class="product-img lazy-img" alt="sth"> <img data-src="images/products/sth.png" class="product-img lazy-img" alt="sth"> </picture> </a> <p class="product-descr"><b>Sth</b></p> </div>
它长时间正常工作。所以,这意味着我应该这样做吗?:
<div class="product-container"> <a href="sth.html"> <picture> <source data-srcset="images/products/sth.webp" type="image/webp" class="product-img" loading="lazy" alt="sth"> <source data-srcset="images/products/sth.png" type="image/png" class="product-img" loading="lazy" alt="sth"> <img data-src="images/products/sth.png" class="product-img" loading="lazy" alt="sth"> </picture> </a> <p class="product-descr"><b>Sth</b></p> </div>
但是其他浏览器会怎样?而且它仍然不能解决来自控制台的警告。