在Web开发中,图片懒加载可以延迟加载页面上的图片,以提高页面加载性能和用户体验。用户在页面加载时不立即加载所有图片,而是等到图片即将进入用户视野时再进行加载。通过延迟加载图片,可以减少初始加载的资源数量,提高页面的加载速度,特别适用于包含大量图片的网页。
定义滚动监听和加载函数:
思路:我们定义一个名为runLazyLoad的函数,它通过监听滚动事件实现了图片的懒加载功能。当页面滚动时,函数会计算滚动距离,并根据一定规则加载新的图片。
函数内部的loadLazyLoadedImages函数用于实际加载图片。它首先获取所有带有data-src属性的图片元素,然后逐个加载这些图片,直到达到指定的加载数量。从而达到懒加载效果。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
   | let previousLoadCount = 0;
  function runLazyLoad(origin) {     loadLazyLoadedImages(origin, 0);     window.addEventListener('scroll', function () {         const scrollDistance = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;         if (scrollDistance > 0) {             const initialLoadCount = Math.floor(scrollDistance / 300) * 9 + 9;             const newLoadCount = initialLoadCount - previousLoadCount;             if (newLoadCount > 0) {                 loadLazyLoadedImages(newLoadCount);                 previousLoadCount = initialLoadCount;             }         }     }); }
   | 
 
 Math.floor(scrollDistance / 300) * 9 + 9;: 每滚动300的距离就加载9张图片进来。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
   | function loadLazyLoadedImages(count) {     const lazyImages = document.querySelectorAll('[data-src]');     let loadedCount = 0;
      lazyImages.forEach(img => {         if (loadedCount >= count) {             return;         }         img.style.backgroundImage = `url(${img.getAttribute('data-src')})`;         img.removeAttribute('data-src');         loadedCount++;     }); }
 
  | 
 
如何使用:
将需要进行懒加载的图片元素添加data-src属性,并将其值设置为对应图片的URL。
html
1
   | <img data-src="path/to/image.webp" alt="Lazy-loaded Image">
   | 
 
javascript
1
   | node.setAttribute('data-src', "path/to/image.webp");
  | 
 
在需要启动的页面,调用runLazyLoad(0); //0 为页面默认需要加载的个数,可以根据需要进行调整。