Last active
April 24, 2018 17:22
-
-
Save joeynimu/f559df14c97e3ce769dcf934a4283837 to your computer and use it in GitHub Desktop.
LazyLoadImages
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
const lazyLoad = () => () => { | |
// create an array from <img /> tags with a .lazy class | |
const lazyImages = Array.from(document.querySelectorAll('img.lazy')) | |
if ('IntersectionObserver' in window && 'IntersectionObserverEntry' in window && 'intersectionRatio' in window.IntersectionObserverEntry.prototype) { | |
let lazyImageObserver = new IntersectionObserver((entries, observer) => { | |
entries.forEach((entry) => { | |
if (entry.isIntersecting) { | |
let lazyImage = entry.target | |
lazyImage.src = lazyImage.dataset.src | |
lazyImage.srcset = lazyImage.dataset.srcset | |
lazyImage.classList.remove('lazy') | |
lazyImageObserver.unobserve(lazyImage) | |
} | |
}) | |
}) | |
lazyImages.forEach(lazyImage => { | |
lazyImageObserver.observe(lazyImage) | |
}) | |
} else { | |
//have a defaulf placeholder | |
} | |
} | |
document.addEventListener('DOMContentLoaded', lazyLoad) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment