Created
October 30, 2018 15:32
-
-
Save FellowshipAgency/ba4ee0fe7d6d9ccb1909a6549201e2af to your computer and use it in GitHub Desktop.
IntersectionObserver
This file contains hidden or 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
// 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