0

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

1 Answers1

0

This happens because of this value: loop: 1. When loading the page in const images = document.querySelectorAll ("[data-src]") are only 6 pictures contained, and when you initialize the slider, it has 10 images. You need to get images and call your observer when the slider is initialized. Siema has an onInit callback. Something like that:

onInit() {
  const el = document.querySelector(this.config.selector); // get siema container
  const images = el.querySelectorAll("[data-src]"); // get all siema images

  images.forEach( image => {
    imgObserver.observe(image);
  });
},

I hope this helps you!

ohladkov
  • 51
  • 7