Skip to content

Instantly share code, notes, and snippets.

@vxhviet
Last active July 25, 2023 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vxhviet/4c830de74c6368f6c1d6e96d47ee292e to your computer and use it in GitHub Desktop.
Save vxhviet/4c830de74c6368f6c1d6e96d47ee292e to your computer and use it in GitHub Desktop.

[JavaScript] - Lazy Loading Images - Intersection Observer API

SOURCE

<div class="features">
        <img
          src="img/digital-lazy.jpg"
          data-src="img/digital.jpg"
          alt="Computer"
          class="features__img lazy-img"
        />
        ...
        
      <img
          src="img/grow-lazy.jpg"
          data-src="img/grow.jpg"
          alt="Plant"
          class="features__img lazy-img"
        />
.lazy-img {
  filter: blur(20px);
}
const imgTargets = document.querySelectorAll('img[data-src]'); // only select the images with `data-src` attribute

const loadImg = function (entries, observer) {
  const [entry] = entries;

  if (!entry.isIntersecting) return;

  // Replace src with data-src
  entry.target.src = entry.target.dataset.src;

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

  observer.unobserve(entry.target);
};

const imgObserver = new IntersectionObserver(loadImg, {
  root: null,
  threshold: 0,
  rootMargin: '200px', // load image before we enter the viewport so that we don't have to wait
});

imgTargets.forEach(img => imgObserver.observe(img));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment