I have a problem with preloading in vue. Problem is that i need to know when the last image has loaded and rendered in the DOM, in order to perform some other stuff. Never mind the data, the images renders etc. What i need to know is how to check for when the last one is loaded and rendered. Figured i could use the imgLoaded from data but that does not make any sense since it does not detect which one’s the last. How can i do this?
Template:
<section v-for="(slice, index) in slices" :key="index" :data-id="index" class="h-screen flex items-center justify-center">
<div class="max-w-[70%]">
<img v-if="index > 0" :src="slice.items[0].image.url" @load="preload">
</div>
</section>
Js
data() {
return {
imgloaded: false
}
},
preload() {
this.imgloaded = true;
},
>Solution :
You can keep track of the number of images loaded using a counter. Initially, this counter will be set to 0. Every time an image loads, you increment this counter. When the counter equals the total number of images, you can consider all images as loaded. Here’s how you can do it:
<template>
<section v-for="(slice, index) in slices" :key="index" :data-id="index" class="h-screen flex items-center justify-center">
<div class="max-w-[70%]">
<img v-if="index > 0" :src="slice.items[0].image.url" @load="preload">
</div>
</section>
</template>
<script>
export default {
data() {
return {
totalImages: this.slices.length - 1,
loadedImages: 0,
allImagesLoaded: false,
}
},
methods: {
preload() {
this.loadedImages += 1;
if (this.loadedImages === this.totalImages) {
this.allImagesLoaded = true;
// All images are loaded, you can perform your tasks here.
}
},
},
}
</script>
In this code, totalImages is the total number of images that need to be loaded, and loadedImages is a counter for the number of images that have already been loaded. allImagesLoaded is a flag indicating whether all images have been loaded.
Every time an image loads, the preload method is called, which increments the loadedImages counter. When loadedImages equals totalImages, it sets allImagesLoaded to true and you can then perform your tasks knowing all images have been loaded.