Skip to content

Instantly share code, notes, and snippets.

@kudinovfedor
Created April 9, 2019 06:52
Show Gist options
  • Save kudinovfedor/8814721fb2221259ad39ff3a43976104 to your computer and use it in GitHub Desktop.
Save kudinovfedor/8814721fb2221259ad39ff3a43976104 to your computer and use it in GitHub Desktop.
<!-- Let's load this in-viewport image normally -->
<img src="hero.jpg" alt=".."/>
<!-- Let's lazy-load the rest of these images -->
<img data-src="unicorn.jpg" loading="lazy" alt=".." class="lazyload"/>
<img data-src="cats.jpg" loading="lazy" alt=".." class="lazyload"/>
<img data-src="dogs.jpg" loading="lazy" alt=".." class="lazyload"/>
<script>
(async () => {
const images = document.querySelectorAll("img.lazyload");
if ('loading' in HTMLImageElement.prototype) {
images.forEach(img => {
img.src = img.dataset.src;
});
} else {
// Dynamically import the LazySizes library
const lazySizesLib = await import('/lazysizes.min.js');
// Initiate LazySizes (reads data-src & class=lazyload)
lazySizes.init(); // lazySizes works off a global.
}
})();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment