我的网页需要显示大约40张图片。对于要从服务器下载的镜像数量,随机导致429错误。
我想保证我的网站显示所有的广告图像。如何避免429请求过多错误?附近有什么工作吗?
发布于 2020-12-01 19:29:33
我使用lazy loading来解决这个问题。如果用户不向下滚动到图像标签本身,则不会向服务器请求图像。
data-src。<img data-src="../img2.png" class="lazy"/>
<img data-src="../img2.png" class="lazy"/>
<img data-src="../img2.png" class="lazy"/>document.addEventListener("DOMContentLoaded", function () {
const lazyLoadImages = document.querySelectorAll(".lazy");
let lazyLoadThrottleTimeout;
function lazyLoading() {
if (lazyLoadThrottleTimeout) {
clearTimeout(lazyLoadThrottleTimeout);
}
lazyLoadThrottleTimeout = setTimeout(function () {
const scrollTop = window.pageYOffset;
lazyLoadImages.forEach(function (image) {
if (image.offsetTop < window.innerHeight + scrollTop) {
image.src = image.dataset.src;
image.classList.remove("w_lazy");
}
});
if (lazyLoadImages.length) {
document.removeEventListener("scroll", lazyLoading);
window.removeEventListener("resize", lazyLoading);
window.removeEventListener("orientationchange", lazyLoading);
}
}, 35);
}
document.addEventListener("scroll", lazyLoading);
window.addEventListener("resize", lazyLoading);
window.addEventListener("orientationchange", lazyLoading);
});其主要思想是eventListener“滚动”和“调整大小”等待,直到用户向下滚动到图像标签,放置src图像路径使用data-src
IntersectionObserver而不是eventListener,然后您将需要为IE用户提供polyfill。https://stackoverflow.com/questions/65087475
复制相似问题