首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当不支持交叉观察者时加载所有图像

当不支持交叉观察者时加载所有图像
EN

Stack Overflow用户
提问于 2022-01-15 14:43:59
回答 1查看 865关注 0票数 0

我用交集观测器来延迟加载图像。如何在不支持交叉观察者的浏览器中加载所有图像?

我的script=

代码语言:javascript
复制
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');
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-15 14:53:55

  1. 也许是IntersectionObserver用聚脂填料
  2. 如果不支持IntersectionObserver,则添加回退代码。
代码语言:javascript
复制
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中不支持解析箭函数:

代码语言:javascript
复制
// change from this
document.querySelectorAll('.lzyp').forEach((pcu) => {
    imob.observe(pcu);
});

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

加在一起:

代码语言:javascript
复制
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);
    });
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70722434

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档