Last active
November 8, 2022 11:00
-
-
Save addyosmani/08da4286144679292f406b75fc4bfab4 to your computer and use it in GitHub Desktop.
Native image lazy-loading with a cross-browser fallback
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
<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