Skip to content

Instantly share code, notes, and snippets.

@maykbrito
Created April 24, 2019 13:18
Show Gist options
  • Save maykbrito/4d8ca0f99ef7b9450463a80e1ece6612 to your computer and use it in GitHub Desktop.
Save maykbrito/4d8ca0f99ef7b9450463a80e1ece6612 to your computer and use it in GitHub Desktop.
simple lazy load background image that resides inside a container
<div class="port-wrapper">
<div class="lazy-image" data-src='/image1.jpg'></div>
<div class="lazy-image" data-src='/image2.jpg'></div>
<div class="lazy-image" data-src='/image3.jpg'></div>
</div>
const images = [...document.querySelectorAll('.lazy-image')];
const interactSettings = {
root: document.querySelector('.port-wrapper'),
rootMargin: '0px 0px 200px 0px',
};
function onIntersection(imageEntites) {
imageEntites.forEach(image => {
if (image.isIntersecting) {
observer.unobserve(image.target);
image.target.setAttribute(
'style',
`background-image:url('${image.target.dataset.src}')`
);
// image.target.src = image.target.dataset.src; //for <img> tag, remove image.target above
image.target.onload = () => image.target.classList.add('loaded');
}
});
}
const observer = new IntersectionObserver(onIntersection, interactSettings);
images.forEach(image => observer.observe(image));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment