不支持路口观察器时加载所有图像

Load all images when intersection observer is not supported

我正在使用路口观察器来延迟加载图像。 如何在不支持 intersection observer 的浏览器中加载所有图像?

我的脚本=

const imob = new IntersectionObserver((entries, self) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            llo(entry.target);
            self.unobserve(entry.target);
        }
    });
});
document.querySelectorAll('.lzyp').forEach((pcu) => {
    imob.observe(pcu);
});

const llo = (pcu) => {
    const img = pcu.querySelector('img');
    const sce = pcu.querySelectorAll('source');

    sce.forEach((sue) => {
        sue.srcset = sue.dataset.srcset;
        sue.removeAttribute('data-srcset');
    });
    img.src = img.dataset.src;
    img.removeAttribute('data-src');
}
  1. 也许 polyfill for IntersectionObserver?

  2. 如果不支持 IntersectionObserver,则添加回退代码。

if (!('IntersectionObserver' in window) ||
    !('IntersectionObserverEntry' in window) ||
    !('intersectionRatio' in window.IntersectionObserverEntry.prototype) ||
    !('isIntersecting' in window.IntersectionObserverEntry.prototype)
) {
    // load all images here
    document.querySelectorAll('.lzyp').forEach( llo );
}

解析箭头功能在IE中不支持:

// change from this
document.querySelectorAll('.lzyp').forEach((pcu) => {
    imob.observe(pcu);
});

// to this
document.querySelectorAll('.lzyp').forEach( function(pcu) {
    imob.observe(pcu);
});

放在一起:

function llo(pcu) {
    const img = pcu.querySelector('img');
    const sce = pcu.querySelectorAll('source');

    sce.forEach((sue) => {
        sue.srcset = sue.dataset.srcset;
        sue.removeAttribute('data-srcset');
    });
    img.src = img.dataset.src;
    img.removeAttribute('data-src');
}

// IntersectionObserver is not supported
if (!('IntersectionObserver' in window) ||
    !('IntersectionObserverEntry' in window) ||
    !('intersectionRatio' in window.IntersectionObserverEntry.prototype) ||
    !('isIntersecting' in window.IntersectionObserverEntry.prototype)
) {
    // load all images here
    document.querySelectorAll('.lzyp').forEach( llo );
} else {
    const imob = new IntersectionObserver( function(entries, self) {
        entries.forEach( function(entry) {
            if (entry.isIntersecting) {
                llo(entry.target);
                self.unobserve(entry.target);
            }
        });
    });
    document.querySelectorAll('.lzyp').forEach(function(pcu) {
        imob.observe(pcu);
    });
}