Skip to content

Instantly share code, notes, and snippets.

@0xtlt
Last active July 29, 2021 08:22
Show Gist options
  • Save 0xtlt/83871db5444a3fd7cdf277445d9f3559 to your computer and use it in GitHub Desktop.
Save 0xtlt/83871db5444a3fd7cdf277445d9f3559 to your computer and use it in GitHub Desktop.
lazy load image set
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.bg-lz-load {
background: white;
}
</style>
</head>
<body>
<div class="bg-lz-load" data-lz="image-set(url('image-1') 1x, url('image-2') 2x)">
</div>
<script>
const OnScreenObserver = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
const element = entry.target;
const visiblePct = Math.floor(entry.intersectionRatio * 100);
if (visiblePct > 10) {
// lazyload execution
element.classList.add('lz-loaded');
element.style.setProperty("background", element.dataset.lz);
OnScreenObserver.unobserve(element);
}
});
},
{ root: null, rootMargin: "0px", threshold: [0.2] },
);
[...document.querySelectorAll(".bg-lz-load:not.lz-loaded")].forEach(el => OnScreenObserver.observe(el));
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment