Skip to content

Instantly share code, notes, and snippets.

@thomaspuppe
Created September 16, 2024 07:14
Show Gist options
  • Save thomaspuppe/88225fcd53f55b84f02244a8ac80d7b4 to your computer and use it in GitHub Desktop.
Save thomaspuppe/88225fcd53f55b84f02244a8ac80d7b4 to your computer and use it in GitHub Desktop.
// HTML
<img data-src="lamas.webp" alt="Lamas!" />
// JavaScript
const images = document.querySelectorAll( 'img[data-src]');
const options = { rootMargin: 'Opx', threshold: 0.5 };
const observer = new IntersectionObserver((entries, observer) => {
entries. forEach (entry => {
if (entry.isIntersecting) {
const image = entry. target;
const src = image.getAttribute( 'data-src');
image. setAttribute( 'src', src); image. removeAttribute( 'data-src' );
observer. unobserve(image);
}
});
}, options)
images.forEach (image => {
observer.observe( image);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment