Skip to content

Instantly share code, notes, and snippets.

@stevepiron
Last active August 5, 2019 16:03
Show Gist options
  • Save stevepiron/06fcde3d4b7836f77e7e921de9d8b669 to your computer and use it in GitHub Desktop.
Save stevepiron/06fcde3d4b7836f77e7e921de9d8b669 to your computer and use it in GitHub Desktop.
Preparing for cross-browser (native) lazy loading
<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