Skip to content

Instantly share code, notes, and snippets.

@addyosmani addyosmani/lazyload.html
Last active May 15, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.