Last active
April 12, 2022 19:30
-
-
Save mrizwan47/509a1107c156e8c6edd69e00df261b8c to your computer and use it in GitHub Desktop.
Minimal VanillaJS LazyLoad Images using Intersection Observer
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Title of the document</title> | |
</head> | |
<body> | |
<img loading="lazy" data-lazy | |
src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkqAcAAIUAgUW0RjgAAAAASUVORK5CYII=" | |
data-src="/path/to/image.jpg" | |
width="1285" height="358" | |
alt=""> | |
</body> | |
</html> |
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
// Lazy Load Images using Intersection Observer | |
var observer = new IntersectionObserver(onIntersect); | |
document.querySelectorAll("[data-lazy]").forEach((img) => { | |
observer.observe(img); | |
}); | |
function onIntersect(entries) { | |
entries.forEach((entry) => { | |
if (entry.target.getAttribute("data-processed") || !entry.isIntersecting) | |
return true; | |
entry.target.setAttribute("src", entry.target.getAttribute("data-src")); | |
entry.target.setAttribute("data-processed", true); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment