Last active
May 25, 2020 00:14
-
-
Save juanallo/9420b04973440742ab68d1fbd574aaf7 to your computer and use it in GitHub Desktop.
Lazy load images with IntersectionObserver
This file contains 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
if(window.IntersectionObserver){ | |
const observe = function (entries, observer) { | |
entries.forEach(function(entry) { | |
if(entry.isIntersecting) { | |
const img = entry.target | |
const src = img.dataset.src | |
const srcset = img.dataset.srcset | |
requestIdleCallback(function () { | |
if(srcset) { | |
img.srcset = srcset | |
} | |
img.src = src | |
}) | |
observer.unobserve(img) | |
} | |
}) | |
} | |
const observer = new IntersectionObserver(observe, {}) | |
const images = document.querySelectorAll('img.lazy') | |
images.forEach(function(img) { | |
observer.observe(img) | |
}) | |
} | |
else { | |
const images = document.querySelectorAll('img.lazy') | |
for(let i=0 ; i < images.length; i++){ | |
const img = images[i] | |
const src = img.dataset.src | |
const srcset = img.dataset.srcset | |
if(srcset) { | |
img.srcset = srcset | |
} | |
img.src = src | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment