Last active
July 29, 2021 08:22
-
-
Save 0xtlt/83871db5444a3fd7cdf277445d9f3559 to your computer and use it in GitHub Desktop.
lazy load image set
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 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