Created
April 24, 2019 13:18
-
-
Save maykbrito/4d8ca0f99ef7b9450463a80e1ece6612 to your computer and use it in GitHub Desktop.
simple lazy load background image that resides inside a container
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
<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> |
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 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