[英]Load all images when intersection observer is not supported
我正在使用交叉点观察器来延迟加载图像。 如何在不支持交叉点观察器的浏览器中加载所有图像?
我的脚本=
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');
}
也许是IntersectionObserver的填充物?
如果不支持 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 );
}
解决箭头 function 在 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);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.