Created
July 30, 2018 08:00
-
-
Save Adam-Mould/6ffa61e3c80b20e90eae7ab53dd6610e to your computer and use it in GitHub Desktop.
Lazy Load Images using IntersectionObserver
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
function imageLazyLoad() { | |
const images = Array.from(document.querySelectorAll('img[data-src]')); | |
if (images.length) { | |
if ('IntersectionObserver' in window) { | |
setupIntersectionObserver(images); | |
} else { | |
loadImages(images); | |
} | |
} | |
} | |
function setupIntersectionObserver(images) { | |
const observer = new IntersectionObserver(onIntersection); | |
images.forEach(image => observer.observe(image)); | |
} | |
function onIntersection(entries, observer) { | |
entries.forEach((entry) => { | |
if (entry.intersectionRatio > 0) { | |
observer.unobserve(entry.target); | |
loadImage(entry.target); | |
} | |
}); | |
} | |
function loadImages(images) { | |
images.forEach(loadImage); | |
} | |
function loadImage(image) { | |
image.setAttribute('src', image.getAttribute('data-src')); | |
image.onload = () => { | |
image.removeAttribute('data-src'); | |
image.removeAttribute('data-srcset'); | |
}; | |
} | |
export default imageLazyLoad; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment