docs/.vitepress/theme/components/extrepo/LazyIcon.vue
49 lines · 1292 bytes
1<script setup lang="ts">
2import { onBeforeUnmount, onMounted, ref } from 'vue'
3import { scheduleIconLoad } from './iconQueue'
4
5const props = defineProps<{
6 src?: string
7 alt: string
8}>()
9
10const rootRef = ref<HTMLElement>()
11const loaded = ref(false)
12const failed = ref(false)
13let observer: IntersectionObserver | undefined
14
15onMounted(() => {
16 const el = rootRef.value
17 if (!el || !props.src) return
18 // Preload a bit before the card is actually visible so it's ready by the time it scrolls in.
19 observer = new IntersectionObserver((entries) => {
20 if (!entries.some(entry => entry.isIntersecting)) return
21 observer?.disconnect()
22 scheduleIconLoad(() => new Promise<void>((resolve) => {
23 const img = new Image()
24 img.onload = () => {
25 loaded.value = true
26 resolve()
27 }
28 img.onerror = () => {
29 failed.value = true
30 resolve()
31 }
32 img.src = props.src!
33 }))
34 }, { rootMargin: '200px' })
35 observer.observe(el)
36})
37
38onBeforeUnmount(() => observer?.disconnect())
39</script>
40
41<template>
42 <img v-if="loaded" ref="rootRef" :src="src" :alt="alt" />
43 <span
44 v-else
45 ref="rootRef"
46 class="ext-site-icon-fallback"
47 :class="{ 'i-lucide:globe': !src || failed, 'ext-site-icon-loading': src && !failed }"
48 />
49</template>