Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR HTML

Lazy loading images

const imgTargets = document.querySelectorAll("img[data-src]");

const imgObserve = function (entries, observer) {
  const [entry] = entries;
  console.log(entry);

  //replace src with data-src
  if (!entry.isIntersecting) {
    return;
  }
  entry.target.src = entry.target.dataset.src;

  //load event
  entry.target.addEventListener("load", function () {
    entry.target.classList.remove("lazy-img");
  });

  observer.unobserve(entry.target);
};

const imgOptions = {
  root: null,
  threshold: 0,
  rootMargin: "200px",
};

const imgObserver = new IntersectionObserver(imgObserve, imgOptions);

imgTargets.forEach(function (img) {
  imgObserver.observe(img);
});
Source by web.dev #
 
PREVIOUS NEXT
Tagged: #Lazy #loading #images
ADD COMMENT
Topic
Name
6+9 =