Created
February 6, 2021 23:44
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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