Skip to content

Instantly share code, notes, and snippets.

@FellowshipAgency
Created October 30, 2018 15:32
Show Gist options
  • Save FellowshipAgency/ba4ee0fe7d6d9ccb1909a6549201e2af to your computer and use it in GitHub Desktop.
Save FellowshipAgency/ba4ee0fe7d6d9ccb1909a6549201e2af to your computer and use it in GitHub Desktop.
IntersectionObserver
// IntersectionObserver
// Used with Rubious plugin and lazy load images
var images = document.querySelectorAll('[data-lazy-src]');
var config = {
rootMargin: '0px 0px 400px 0px',
threshold: 0 };
var loaded = 0;
var observer = new IntersectionObserver(function (entries, self) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
// console.log(`Image ${entry.target.src} is in the viewport!`);
preloadImage(entry.target);
// Stop watching and load the image
self.unobserve(entry.target);
}
});
}, config);
images.forEach(function (image) {
observer.observe(image);
});
function preloadImage(img) {
var srcset = img.getAttribute('data-lazy-srcset');
if (srcset) {img.srcset = srcset;}
var src = img.getAttribute('data-lazy-src');
if (src) {img.src = src;}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment