Last active
August 5, 2019 16:03
-
-
Save stevepiron/06fcde3d4b7836f77e7e921de9d8b669 to your computer and use it in GitHub Desktop.
Preparing for cross-browser (native) lazy loading
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
<noscript> | |
<img src="image.jpg"> | |
</noscript> | |
<img data-src="image.jpg" loading="lazy"> | |
<script> | |
if ('loading' in HTMLImageElement.prototype) { | |
const lazy = document.querySelectorAll('[data-src]'); | |
lazy.forEach(el => { | |
// Turn `data-src` into `src` | |
el.src = el.dataset.src; | |
// Same for `data-srcset` if used | |
if (el.dataset.srcset) { | |
el.srcset = el.dataset.srcset; | |
} | |
}); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment