-
Notifications
You must be signed in to change notification settings - Fork 6
/
LazyImage.svelte
72 lines (61 loc) · 1.35 KB
/
LazyImage.svelte
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<script>
import { onMount } from 'svelte';
/**
* Path to placeholder image.
* @type {string}
*/
export let placeholder;
/**
* Path to image.
* @type {string}
*/
export let src;
/**
* Alt image text description for accessibility.
* @type {string}
*/
export let alt;
/**
* IntersectionObserver options
* @type {{ root: any; rootMargin: string; threshold: number; }}
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/IntersectionObserver}
*/
export let options = { root: null, rootMargin: '0px 0px 0px 0px', threshold: 0.0 };
let imgElement;
let path;
let observer;
let intersected = false;
let loaded = false;
$: path = intersected ? src : placeholder;
$: cssClass = $$props.class || '';
onMount(() => {
observer = new IntersectionObserver((entries, self) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
intersected = true;
self.unobserve(imgElement);
}
});
}, options);
observer.observe(imgElement);
return () => {
if (observer) {
observer.unobserve(imgElement);
}
};
});
function handleLoad() {
if (!loaded && path === src) {
loaded = true;
}
}
</script>
<img
src={path}
{alt}
on:load={handleLoad}
bind:this={imgElement}
{...$$restProps}
class="svelte-lazy-image {cssClass}"
class:svelte-lazy-image--loaded={loaded}
/>