Skip to content

Instantly share code, notes, and snippets.

@addyosmani
Last active November 8, 2022 11:00
Show Gist options
  • Save addyosmani/08da4286144679292f406b75fc4bfab4 to your computer and use it in GitHub Desktop.
Save addyosmani/08da4286144679292f406b75fc4bfab4 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