'VueJs 3: How to load and apply some operations on a component without mounting it
Short version: Is it possible to create a virtual node outside of the DOM to preload images, seek videos... without ever mounting it in the real DOM?
Long version:
In order to do a slide show in VueJs, I would like to be sure that the next slide appears only when it is fully initialized. It means that images and videos should not only be loaded, but I may also need to do some operations that take some time, like seeking to a position in a video...
To that end, I created an async function beforeChangePage that is called before the page change. Unfortunately, I don't know how to make it "preload" the component without mounting it on the DOM. So for now what happens is that the slide is displayed, and then the images are fetched (I volontary used an image taking 3 seconds to appear). Similarly, the video is likely to be seeked after being displayed, leading to a glitch.
Note that I guess I could use a mix of CSS hidden: true to mount the slide a few pages before, ensuring that the images are properly loaded, however I'd like to find a solution that works completely outside the DOM.
You can find a full demo here.
The component that should be preloaded being:
<script>
import { ref, inject, provide, resolveComponent } from 'vue'
export default {
beforeChangePage: async () => {
await new Promise(r => setTimeout(r, 0)); // Just to check that the transition can wait some events
console.log("Can I mount without inserting in the DOM at that step to preload images?");
console.log("Can I fetch the video at that step to ensure the video is at the good position?")
console.log("Something like:");
// let video = document.getElementById("video");
// video.currentTime = 5.2;
// await new Promise(r => {
// video.addEventListener('seeked', (event) => {
// r()
// });)
}
}
</script>
<script setup>
let page = inject("page", 42);
</script>
<template>
<div v-if="page == 1">
I present here a second concept with an image looong to load. I don't want it to be mounted before the image is loaded. Ideally, I would load the images without even needing to list all images.<br/>
<img src="http://www.deelay.me/3000/http://placekitten.com/300/200"/>
I also have a video, and I don't want to mount it before the video is on time 5.2. The goal of beforeChangePage is to ensure that this is ture.
<video>
<source src="http://www.w3schools.com/html/mov_bbb.mp4"/>
</video>
</div>
</template>
Solution 1:[1]
For Images you can use Image()
var imgpreload = new Image();
imgpreload.onload = function() {
// do stuff on image load
};
imgpreload.src = "/path/to/image.jpg"; // this has to be after `onload` event otherwise you'll face race condition
but for videos i don't think you can do it outside the DOM
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ergec |
