0

This is my first time attempting Lazy Loading, and I wanted to use IntersectionObserver. Got started by following along with this website. I honestly just want the content of the page to wait to load until it is less than 50% of the viewport's width below the viewport. I'm not sure how to observe all content, so I just selected the classes for the widgets that are being displayed, as they are the main content. Unfortunately my code doesn't seem to be doing much. I added a console.log at the beginning to make sure the file was linked correctly, and I tried to add more console.logs to log when the widget moves in and out of the capture area. The first console.log works, but nothing else happens.

Here is what I have:

console.log('file loaded');
const widgets = document.querySelectorAll('.widget');
const config = {
  root: null,
  rootMargin: '-50px 0px -55% 0px',
  threshold: .5
};

let isLeaving = false;
let observer = new IntersectionObserver(function(entries, self) {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      // we are ENTERING the "capturing frame". Set the flag.
      isLeaving = true;
      // Do something with entering entry
      console.log("Widget loaded.");
      self.unobserve(entry.target);
    } else if (isLeaving) {
      // we are EXITING the "capturing frame"
      isLeaving = false;
      // Do something with exiting entry
      console.log("Widget is exiting.")

    }
});
}, config);

widgets.forEach(widget => {
  observer.observe(widget);
});

This code is in it's own js file. Where should I be linking it in the HTML file? I'd appreciate any help I can get! Let me know if I need to provide more information.

  • @Eldar I thought that was what the code at the bottom was for? Cycling through each widget I selected at the top? –  Dec 10 '19 at 19:47
  • check if document.querySelectorAll('.widget') returns as you expected – duc mai Dec 12 '19 at 20:17

0 Answers0