Lib: Implement LazyImage component (images will be loaded once visible)
This commit is contained in:
42
src/lib/components/LazyImage.svelte
Normal file
42
src/lib/components/LazyImage.svelte
Normal file
@ -0,0 +1,42 @@
|
||||
<script lang="ts">
|
||||
import type { HTMLImgAttributes } from "svelte/elements";
|
||||
import { lazyload } from "$lib/lazyload";
|
||||
|
||||
interface LazyImageProps extends HTMLImgAttributes {
|
||||
/** The URL to the image resource to lazyload */
|
||||
src: string;
|
||||
}
|
||||
|
||||
let { src, ...restProps }: LazyImageProps = $props();
|
||||
|
||||
const blobToBase64 = (blob: Blob): Promise<any> => {
|
||||
return new Promise((resolve, _) => {
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => resolve(reader.result);
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
};
|
||||
|
||||
const loadImage = async (url: string): Promise<any> => {
|
||||
return await fetch(url)
|
||||
.then((response) => response.blob())
|
||||
.then((blob) => blobToBase64(blob));
|
||||
};
|
||||
|
||||
const lazy_visible_handler = () => {
|
||||
load = true;
|
||||
};
|
||||
|
||||
// Once the image is visible, this will be set to true, triggering the loading
|
||||
let load: boolean = $state(false);
|
||||
</script>
|
||||
|
||||
<div use:lazyload onLazyVisible={lazy_visible_handler}>
|
||||
{#if load}
|
||||
{#await loadImage(src)}
|
||||
<!-- Loading... -->
|
||||
{:then data}
|
||||
<img src={data} {...restProps} />
|
||||
{/await}
|
||||
{/if}
|
||||
</div>
|
30
src/lib/lazyload.ts
Normal file
30
src/lib/lazyload.ts
Normal 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);
|
||||
},
|
||||
};
|
||||
};
|
Reference in New Issue
Block a user