如果是类似瀑布流,一个页面有无数图片的,也可以使用交错加载的方法,将图片加载过程分为多个小任务。
这样子,上面的代码就变成下面这样子,希望对大家有用。
<javascript> // 获取页面可视区域的高度 const visibleHeight = window.innerHeight;
// 获取页面上所有具有指定 class 的图片元素 const imgs = document.querySelectorAll(".my-lazy-load-class img");
// 为每个图片元素添加 data-src 属性 for (const img of imgs) { img.setAttribute("data-src", img.src); img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAIBRAA7"; }
// 使用交错加载技术,将图片加载过程分为多个小任务 let loadedImages = 0; const loadBatch = 5; function loadImages() { for (let i = 0; i < loadBatch && loadedImages < imgs.length; i++) { const img = imgs[loadedImages]; // 获取图片元素的顶部和底部位置 const rect = img.getBoundingClientRect(); const top = rect.top; const bottom = rect.bottom;
// 如果图片元素的顶部或底部位置距离可视区域顶部距离小于阈值 if ((top <= visibleHeight && bottom >= 0) || (bottom >= 0 && top <= visibleHeight + threshold)) { img.src = img.getAttribute("data-src"); loadedImages++; } } if (loadedImages < imgs.length) { setTimeout(loadImages, 200); } }
// 设置阈值和延迟 const threshold = 100;
// 节流函数 let throttleTimeout; function throttleScroll() { if (throttleTimeout) { return; } throttleTimeout = setTimeout(() => { throttleTimeout = null; loadImages(); }, 200); }
// 监听滚动事件 window.addEventListener("scroll", throttleScroll);
// 初始加载一次 loadImages(); </javascript>
|