I implemented Intersection Observer on my Wordpress site which is on dev mode atm and just the last image at the bottom of the site is lazyloading.
Not sure the reason why that is happening. See below my lazy code.
/*Lazy load images*/
const allViews = document.querySelectorAll("[data-src]");
function preloadImage(img) {
const src = img.getAttribute("data-src");
if (!src) {
return;
}
img.src = src;
}
const options = {
root: null,
threshold: 0,
rootMargin: "0px",
};
const callback = function (entries) {
//console.log(entries);
};
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach((entry) => {
if (!entry.isIntersecting) {
return;
} else {
console.log(entry.target);
preloadImage(entry.target);
observer.unobserve(entry.target);
}
});
}, options);
allViews.forEach((image) => {
observer.observe(image);
});
On another file, I have a jquery script adding the data-src attribute to all images and adding the lazyload class:
/*change img src to img data-src for lazy load*/
$("img").each(function () {
$(this).attr("data-src", $(this).attr("src"));
$(this).addClass('lazyload');
//$(this).removeAttr("src");
//console.log($(this)[0].outerHTML);
});
Any help will be great.
I'm still confused why are you actually using this method because wordpress already has native loading="lazy" support