Skip to content

Instantly share code, notes, and snippets.

@andreasvirkus
Created August 8, 2019 11:17
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 andreasvirkus/76c7e1c4628480eddb731ae08da3c7c3 to your computer and use it in GitHub Desktop.
Save andreasvirkus/76c7e1c4628480eddb731ae08da3c7c3 to your computer and use it in GitHub Desktop.
<body>
<blockquote>
<p>Photos by <a href="https://source.unsplash.com/">random photographers</a> on <a href="https://unsplash.com/">Unsplash</a></p>
</blockquote>
<main>
<img lazy data-src="https://source.unsplash.com/random/800x600">
<img lazy data-src="https://source.unsplash.com/random/800x600">
<img lazy data-src="https://source.unsplash.com/random/800x600">
<img lazy data-src="https://source.unsplash.com/random/800x600">
<img lazy data-src="https://source.unsplash.com/random/800x600">
<img lazy data-src="https://source.unsplash.com/random/800x600">
<img lazy data-src="https://source.unsplash.com/random/800x600">
<img lazy data-src="https://source.unsplash.com/random/800x600">
<img lazy data-src="https://source.unsplash.com/random/800x600">
<img lazy data-src="https://source.unsplash.com/random/800x600">
<img lazy data-src="https://source.unsplash.com/random/800x600">
<img lazy data-src="https://source.unsplash.com/random/800x600">
<img lazy data-src="https://source.unsplash.com/random/800x600">
<img lazy data-src="https://source.unsplash.com/random/800x600">
<img lazy data-src="https://source.unsplash.com/random/800x600">
<img lazy data-src="https://source.unsplash.com/random/800x600">
<img lazy data-src="https://source.unsplash.com/random/800x600">
<img lazy data-src="https://source.unsplash.com/random/800x600">
<img lazy data-src="https://source.unsplash.com/random/800x600">
<img lazy data-src="https://source.unsplash.com/random/800x600">
<img lazy data-src="https://source.unsplash.com/random/800x600">
<img lazy data-src="https://source.unsplash.com/random/800x600">
</main>
<script src="/lazyLoad.js">
</body>
// Let's lazy load images via the IntersectionObserver API
const images = [...document.querySelectorAll('img[lazy]')]
const options = {
root: document.querySelector('main'), // Or wherever you wish your images to be lazy-loaded
rootMargin: '0px 0px 200px 0px'
}
function onIntersection (imageEntities) {
imageEntities.forEach(image => {
if (image.isIntersecting) {
observer.unobserve(image.target)
image.target.src = image.target.dataset.src
}
})
}
const observer = new IntersectionObserver(onIntersection, options)
images.forEach(image => observer.observe(image))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment