I have this fiddle to show my problem.
I have made an intersection observer for lazy loading images, code:
const images = document.querySelectorAll("[data-src]");
function preloadImage(img){
const src = img.getAttribute("data-src");
if (!src) { return; }
img.src= src;
}
const imgOptions = {
threshold: 0,
rootMargin: "0px 0px 300px 0px"
};
const imgObserver = new IntersectionObserver( (entries, imgObserver) => {
entries.forEach(entry => {
if(!entry.isIntersecting){
return;
} else {
preloadImage(entry.target);
imgObserver.unobserve(entry.target);
}
})
}, imgOptions);
images.forEach( image => {
imgObserver.observe(image);
});
The problem arises when I loop through the Siema carousel, the last and first images "unloads", meaning, src
is returned to data-src
, despite it being told to unobserve
after intersecting.
To see the problem simply click 'prev' in the fiddle. The first image will disappear, but it was already loaded.
Why is this happening, what am I doing wrong?
EDIT: Fixed working fiddle, thank you @ohladkov