Skip to content

Instantly share code, notes, and snippets.

@mrizwan47
Last active April 12, 2022 19:30
Show Gist options
  • Save mrizwan47/509a1107c156e8c6edd69e00df261b8c to your computer and use it in GitHub Desktop.
Save mrizwan47/509a1107c156e8c6edd69e00df261b8c to your computer and use it in GitHub Desktop.
Minimal VanillaJS LazyLoad Images using Intersection Observer
<!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>
// 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