Last active
March 22, 2021 15:56
-
-
Save gka/0d48bfad32da32eeb6279d67755cd5b2 to your computer and use it in GitHub Desktop.
svelte 3 lazyload example
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
<h1>lazyload example</h1> | |
{#each [0,1,2,3,4,5,6,7,8,9] as i} | |
<p>Scroll down to load the images. Quo et qui laboriosam rerum. Animi et quia consequuntur quas sit eaque molestias. Accusamus voluptate nulla eligendi. Dolores labore ea asperiores ut voluptas dolorem. Cupiditate in enim quibusdam. Quas quae aliquam sed repellat laboriosam inventore est.</p> | |
<img alt="random image" use:lazyload src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAQAAABeK7cBAAAAC0lEQVR42mNkAAIAAAoAAv/lxKUAAAAASUVORK5CYII=" data-src="https://picsum.photos/500/300/?image={i}" /> | |
{/each} | |
<script> | |
import { lazyload } from './lazyload.js'; | |
</script> |
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
const observer = new IntersectionObserver(entries => { | |
entries.forEach(entry => { | |
const img = entry.target; | |
if (img.dataset.src && entry.intersectionRatio !== 0) { | |
img.setAttribute('src', img.dataset.src); | |
delete img.dataset.src; | |
} | |
}) | |
}, { rootMargin: '-100px' }); | |
export function lazyload(node) { | |
observer.observe(node); | |
return { | |
destroy() { | |
observer.unobserve(node); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment