I'm using intersection observer for late loading images. How can I load all images in browsers that don't support intersection observer?
My script=
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');
}
Maybe a polyfill for IntersectionObserver?
Adding fallback code if 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 );
}
Resolve Arrow function is not supported in IE:
// change from this
document.querySelectorAll('.lzyp').forEach((pcu) => {
imob.observe(pcu);
});
// to this
document.querySelectorAll('.lzyp').forEach( function(pcu) {
imob.observe(pcu);
});
put together:
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);
});
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments