Skip to content

Instantly share code, notes, and snippets.

@danBamikiya
Forked from addyosmani/lazyload.html
Created May 10, 2021 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danBamikiya/be09e40b2762aa9b0fe9dacd68ec78cc to your computer and use it in GitHub Desktop.
Save danBamikiya/be09e40b2762aa9b0fe9dacd68ec78cc to your computer and use it in GitHub Desktop.
Native image lazy-loading with a cross-browser fallback
<img data-src="unicorn.jpg" loading="lazy" alt=".." class="lazyload"/>
<script>
// Select all images with the class "lazyload"
const images = document.querySelectorAll("img.lazyload");
// Check if the browser supports the "loading" attribute
if ('loading' in HTMLImageElement.prototype) {
// If so, we'll update all <img src> to point to the data-src instead
images.forEach(img => {
img.src = img.dataset.src;
});
} else {
// If the browser doesn't support the "loading" attribute
// Fetch and apply a fallback. Here we use the LazySizes library
// By default it initializes on images with class="lazyload" w/data-src
const lazySizes = await import("lazysizes.js");
lazySizes.init();
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment