图片延迟加载可以显著提高网页性能,尤其是对于包含大量图片或资源的页面。延迟加载的优点在于它避免了用户没有浏览到的内容被提前加载,从而减少了初始加载时间和网络带宽的消耗。

本文讲如何使用IntersectionObserver()实现图片延迟加载。示例如下:
https://10.1pxeye.com/docs/element-in-viewport/

代码:
const loadImages = (entries, observer) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            const imgElement = entry.target;
            const imgSrc = imgElement.dataset.imgSrc;
            imgElement.style.backgroundImage = `url('${imgSrc}')`;
            observer.unobserve(imgElement);
        }
    });
};

const showImgInViewport = () => {
    const observerOptions = {
        rootMargin: '100px', // Load images before they enter the viewport
        threshold: 0.1 // When 10% of the image is visible
    };

    const observer = new IntersectionObserver(loadImages, observerOptions);
    document.querySelectorAll('[data-img-src]').forEach(imgElement => {
        observer.observe(imgElement);
    });
};

showImgInViewport();
IntersectionObserver 的优点
参考文档

https://developer.mozilla.org/zh-CN/docs/Web/API/IntersectionObserver