Skip to content

Instantly share code, notes, and snippets.

@yakuzaaaa
Last active February 21, 2019 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yakuzaaaa/3ea510f62228f02a0503b3a646fc1eba to your computer and use it in GitHub Desktop.
Save yakuzaaaa/3ea510f62228f02a0503b3a646fc1eba to your computer and use it in GitHub Desktop.
document.addEventListener("DOMContentLoaded", function() {
const images = [].slice.call(document.querySelectorAll("lazy-image"));
if ("IntersectionObserver" in window) {
/**
We first check if API in available and then continue to create a simple IntersectionObserver
*/
let lazyImageObserver = new IntersectionObserver((entries, observer) => {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
let image = entry.target;
image.src = image.dataset.src;
image.classList.remove("lazy");
lazyImageObserver.unobserve(image);
}
});
});
images.forEach((lazyImage) => {
/**
Telling the Observer to observe each lazyImage
*/
lazyImageObserver.observe(lazyImage);
});
} else {
/**
Fallback to use our slow solution using scroll listener
*/
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment