Lazy loading Images
Sat Oct 01 2022 07:30:25 GMT+0000 (Coordinated Universal Time)
Saved by
@Kristi
#javascript
//HTML
<img
src="img/digital-lazy.jpg"
data-src="img/digital.jpg"
alt="Computer"
class="features__img lazy-img"
/>
//CSS
.lazy-img {
filter: blur(20px);
}
//Lazy loading Images
const imgTargets = document.querySelectorAll('img[data-src]');
const loadImage = (entries, observer) => {
const [entry] = entries;
if (!entry.isIntersecting) return;
//Replace src with data-src
entry.target.src = entry.target.dataset.src;
//Remove lazy-img class after img has been loaded
entry.target.addEventListener('load', function () {
entry.target.classList.remove('lazy-img');
});
observer.unobserve(entry.target);
};
const imgObserver = new IntersectionObserver(loadImage, {
root: null,
threshold: 0,
rootMargin: '200px',
});
imgTargets.forEach(img => imgObserver.observe(img));
content_copyCOPY
Comments