feat: lazy load images (#1969)

This commit is contained in:
Shinigami 2023-04-26 22:46:00 +02:00 committed by GitHub
parent 1ceb3e2857
commit 23c1dfec10
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 57 additions and 48 deletions

View file

@ -1,8 +1,6 @@
<script setup lang="ts">
import { decode } from 'blurhash'
const { blurhash, src, srcset, shouldLoadImage = true } = defineProps<{
blurhash?: string | null | undefined
const { blurhash = '', src, srcset, shouldLoadImage = true } = defineProps<{
blurhash?: string
src: string
srcset?: string
shouldLoadImage?: boolean
@ -11,44 +9,8 @@ const { blurhash, src, srcset, shouldLoadImage = true } = defineProps<{
defineOptions({
inheritAttrs: false,
})
const isLoaded = ref(false)
const placeholderSrc = $computed(() => {
if (!blurhash)
return ''
const pixels = decode(blurhash, 32, 32)
return getDataUrlFromArr(pixels, 32, 32)
})
function loadImage() {
const img = document.createElement('img')
img.onload = () => {
isLoaded.value = true
}
img.src = src
if (srcset)
img.srcset = srcset
setTimeout(() => {
isLoaded.value = true
}, 3_000)
}
onMounted(() => {
if (shouldLoadImage)
loadImage()
})
watch(() => shouldLoadImage, () => {
if (shouldLoadImage)
loadImage()
})
</script>
<template>
<img v-if="isLoaded || !placeholderSrc" v-bind="$attrs" :src="src" :srcset="srcset">
<img v-else v-bind="$attrs" :src="placeholderSrc">
<UnLazyImage v-bind="$attrs" :blurhash="blurhash" :src="src" :src-set="srcset" :lazy-load="shouldLoadImage" auto-sizes />
</template>

View file

@ -214,7 +214,7 @@ watch(shouldLoadAttachment, () => {
@click="!shouldLoadAttachment ? loadAttachment() : openMediaPreview(attachments ? attachments : [attachment], attachments?.indexOf(attachment) || 0)"
>
<CommonBlurhash
:blurhash="attachment.blurhash"
:blurhash="attachment.blurhash || ''"
class="status-attachment-image"
:src="src"
:srcset="srcset"