add image lazy loading

This commit is contained in:
Tomáš Mládek 2021-01-09 20:53:56 +01:00
parent 22ee6f50cf
commit af7e345b2f

View file

@ -1,11 +1,10 @@
<template>
<div class="video-scroll">
<div class="video-scroll" ref="root">
<img v-for="(file, idx) in definition.files"
:src="file"
:data-src="file"
:style="{
top: `${Math.round(definition.top)}px`,
left: `${Math.round(definition.left) + width * idx}px`,
...definition.style
}"
/>
@ -13,7 +12,7 @@
</template>
<script lang="ts">
import {defineComponent, ref} from "vue";
import {defineComponent, onMounted, ref} from "vue";
export default defineComponent({
name: "VideoScroll",
@ -24,9 +23,9 @@ export default defineComponent({
}
},
setup(props) {
console.debug(props.definition);
const width = ref(0);
const height = ref(0);
const root = ref<Element | null>(null);
const definition = props.definition as VideoScrollDef;
getMeta(definition.files[0]).then((img) => {
@ -34,7 +33,22 @@ export default defineComponent({
height.value = img.height;
});
onMounted(() => {
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting){
const element = entry.target as HTMLImageElement;
element.src = element.dataset.src!;
}
})
}, {rootMargin: "100px"});
Array.from((root.value as Element).children).forEach((el) => {
observer.observe(el);
});
});
return {
root,
width,
height
};