Skip to content

Instantly share code, notes, and snippets.

@Adam-Mould
Created July 30, 2018 08:00
Show Gist options
  • Save Adam-Mould/6ffa61e3c80b20e90eae7ab53dd6610e to your computer and use it in GitHub Desktop.
Save Adam-Mould/6ffa61e3c80b20e90eae7ab53dd6610e to your computer and use it in GitHub Desktop.
Lazy Load Images using IntersectionObserver
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