Skip to content

Instantly share code, notes, and snippets.

@deanhume
Last active May 20, 2021 17:55
Show Gist options
  • Save deanhume/1da60330fa8f6dc3d0f4885168a48f9e to your computer and use it in GitHub Desktop.
Save deanhume/1da60330fa8f6dc3d0f4885168a48f9e to your computer and use it in GitHub Desktop.
Intersection Observer - Image lazy load
// Get all of the images that are marked up to lazy load
const images = document.querySelectorAll('.js-lazy-image');
const config = {
// If the image gets within 50px in the Y axis, start the download.
rootMargin: '50px 0px',
threshold: 0.01
};
// The observer for the images on the page
let observer = new IntersectionObserver(onIntersection, config);
images.forEach(image => {
observer.observe(image);
});
@samouss
Copy link

samouss commented Aug 10, 2017

+1

@LexSwed
Copy link

LexSwed commented Aug 18, 2017

line's missing

let observer = new IntersectionObserver(onIntersection, config);
function onIntersection(images, observer) {
  images.forEach(image => {
    observer.observe(image);
  });
}

@talldan
Copy link

talldan commented Aug 29, 2017

Looking at the api, it should be:

let observer = new IntersectionObserver(onIntersection, config);
images.forEach(image => {
  observer.observe(image);
});

@deanhume
Copy link
Author

Good spot all - updated!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment