Skip to content

Instantly share code, notes, and snippets.

@steveshead
Created February 6, 2021 23:44
Show Gist options
  • Save steveshead/3347dfab732a952d0694005e34703ac0 to your computer and use it in GitHub Desktop.
Save steveshead/3347dfab732a952d0694005e34703ac0 to your computer and use it in GitHub Desktop.
[Javascript Lazy Loading Images] Lazy loading images with vanilla javascript and the Intersection Observer API
const imgTargets = document.querySelectorAll('img[data-src]');
const loadImg = function (entries, observer) {
const [entry] = entries;
if (!entry.isIntersecting) return;
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',
});
imgTargets.forEach(img => imgObserver.observe(img));
/*
Assumptions are you have a smaller, lower resolution image as a placeholder and 'data-src' in the img tag similar to below:
<img
src="img/digital-lazy.jpg" // tiny version of the image
data-src="img/digital.jpg" // actual image
alt="Computer"
class="features__img lazy-img" // lazy-img class
/>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment