Lib: Implement LazyImage component (images will be loaded once visible)

This commit is contained in:
2024-12-16 02:27:45 +01:00
parent 57cae4d400
commit 14516133de
2 changed files with 72 additions and 0 deletions

30
src/lib/lazyload.ts Normal file
View File

@ -0,0 +1,30 @@
// https://www.alexschnabl.com/blog/articles/lazy-loading-images-and-components-in-svelte-and-sveltekit-using-typescript
let observer: IntersectionObserver;
const getObserver = () => {
if (observer) return;
observer = new IntersectionObserver((entries: IntersectionObserverEntry[]) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
entry.target.dispatchEvent(new CustomEvent("LazyVisible"));
}
});
});
};
// This is used as an action on lazyloaded elements
export const lazyload = (node: HTMLElement) => {
// The observer determines if the element is visible on screen
getObserver();
// If the element is visible, the "LazyVisible" event will be dispatched
observer.observe(node);
return {
destroy() {
observer.unobserve(node);
},
};
};