Exploring VueJs 3: Strategies for loading and implementing actions on a component before mounting

Briefly: Can a virtual node be created outside of the DOM to preload images, seek videos... without ever being mounted in the real DOM?

Detailed version:

I want to ensure that the next slide appears only when it is fully initialized for a slideshow in VueJs. This means not only loading images and videos but also performing tasks that take time, like seeking to a position in a video...

To achieve this, I created an async function beforeChangePage that runs before page change. Unfortunately, I'm unsure how to have it "preload" the component without mounting it on the DOM. Currently, what happens is that the slide displays first, then the images are loaded (I intentionally used an image that takes 3 seconds to appear). Similarly, the video may be seeked after displaying, causing a glitch.

I could potentially use a combination of CSS hidden: true to mount the slide a few pages earlier to ensure images load properly, but I prefer a solution that operates entirely external to the DOM.

You can view the full demo here.

The preloaded component:

<script>
    import { ref, inject, provide, resolveComponent } from 'vue'
    
    export default {
        beforeChangePage: async () => {
            await new Promise(r => setTimeout(r, 0)); // Just to check if transition can wait
            console.log("Can I preload images without inserting in the DOM at this step?");
            console.log("Can I fetch the video now to ensure it's at the correct 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">
    Here is a concept with an image that takes time to load. I don't want it mounted until the image loads. Ideally, images would load without listing each one.<br/>
    <img src="http://www.deelay.me/3000/http://placekitten.com/300/200"/>
    There is also a video that should not be mounted before reaching time 5.2. The aim of beforeChangePage is to ensure this.
    <video>
      <source src="http://www.w3schools.com/html/mov_bbb.mp4"/>
    </video>
  </div>
</template>

Answer №1

When it comes to handling images, you have the option of utilizing the Image() method.

var imgpreload = new Image(); 
imgpreload.onload = function() {
    // Perform actions once the image has loaded
};
imgpreload.src = "/path/to/image.jpg"; // Make sure this follows the `onload` event to avoid race conditions

However, when dealing with videos, it seems that manipulating them outside the DOM may not be possible.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for simulating next/router in vitest for unit testing?

Struggling with creating basic tests for our Next.js application that utilizes the useRouter() hook, encountering errors when using vitest. In search of solutions to mock next/router for unit testing in conjunction with vitest. ...

Obtaining information from node.js module to the server.js script

I am attempting to extract data from a function within a node module, which returns a JSON object. My goal is to display this JSON object in a router located in my server.js file. This is how I am trying to export it: // Function Export exports.g ...

What are the steps to modify the authorization header of an HTTP GET request sent from a hyperlink <a href> element?

I have a unique Angular application that securely saves JWT tokens in localstorage for authentication purposes. Now, I am eager to explore how to extract this JWT token and embed it into an HTTP GET request that opens up as a fresh web page instead of disp ...

Compiling TypeScript files with an incorrect path when importing, appending "index" at the end of the @angular/material library

I'm currently working on creating a library to collect and distribute a series of Angular components across various projects, with a dependency on angular/material2. My objective is to eventually publish it on npm. However, I've encountered an i ...

I'm interested in querying my mongodb collection data based on a particular field

I need help creating a list from my mongodb database that can be sorted by the "username" field. After learning about the limitations of namespaceing in mongodb, I'm trying to figure out how to sort my collection based on the "username" field. Here ...

Having trouble retrieving the full HTML code with the execute_script function in Python while web scraping

Currently, I am in need of HTML code to perform web scraping using Python. The particular website I am working with is that of a real estate agency. Prior to executing the onclick event for a button that changes pages, it is crucial for me to first obtain ...

Swapping out a sequence of characters in a web address with a different set

Swapping out imgur for filmot, Enter URL - https://i.stack.imgur.com/Uguvn.jpg Click the submit button After clicking submit, a new tab should open with the link .filmot.com/abcde.jpg. <html> <head> <title>input</title> <sc ...

Is there a way to incorporate additional text into option text without compromising the existing values?

One challenge I'm facing is adding additional text to the options without changing their values upon selection. Would you be able to assist me with resolving this issue? I have come across the following HTML code: <select id="q_c_0_a_0_name"> ...

Employing a string key to serve as the v-model in a v-item-group

Is it possible to use a string key as v-model on v-item-group? In the data area, I have the following: payment: null, payments: [ { icon: 'mdi-alpha-p-circle-outline', type: 'paypal', }, { ...

Carousel-Owl, glide through two items simultaneously

I am currently in the process of developing a slider using the beta version of Owl-Carousel 2, but I am encountering several issues. My goal is to configure the owlCarousel to function as follows: It should scroll through 2 items at a time while displayin ...

Ways to determine if new data has been added to a MySQL table

Can anyone explain how the Facebook notification system operates? Here is my code snippet: (function retrieve_req() { $.ajax({ url: 'request_viewer_and_its_utilities.php', success: function(data) { $('.inte ...

Tips for reducing the amount of repetitive code in your reducers when working with redux and a plain old JavaScript object (

When it comes to writing reducers for Redux, I often encounter challenges. My struggle usually lies in wrapping a lot of my state manipulation in functions like .map and .slice. As the structure of my state object becomes more complex, the reducers become ...

What are the capabilities of Ajax when it comes to utilizing select controls in J

Is there a way to trigger an ajax call when a select control value is clicked? The onChange event doesn't seem to work for me in this case :( This is what I have tried so far: JAVASCRIPT: <script> function swapContent(cv) { $("#myDiv"). ...

Setting a JavaScript value for a property in an MVC model

I am currently working on an asp.net mvc application and I am in the process of implementing image uploading functionality. Below is the code for the image upload function: $(document).ready(function () { TableDatatablesEditable.init(); ...

Steps for changing a component's properties when the component serves as a property

The scenario I'm facing involves a component that receives a prop named button. This button prop is essentially a Component itself, containing various other props within it. My goal is to override the specific prop called type within this nested struc ...

Bug in timezone calculation on Internet Explorer 11

I've spent hours researching the issue but haven't been able to find any effective workarounds or solutions. In our Angular 7+ application, we are using a timezone interceptor that is defined as follows: import { HttpInterceptor, HttpRequest, H ...

Retrieving chosen items from NextUI-Table

I am completely new to JavaScript and NextUI. My usual work involves C# and DotNET. I have a requirement to create a table with selectable items, and when a button is clicked, all the selected items should be passed to a function on the server that accepts ...

Display header right button based on a condition in React Native using React Navigation

I am looking to conditionally display the Entypo new-message icon in the top right corner of the header based on a boolean variable (if true, then show the icon in the header). Here is a snippet of code where this functionality can be replicated. Thank y ...

Encountering difficulty in accessing game.html following button clicks

Why isn't the redirection to game.html happening after clicking on the buttons in index.html? The file structure consists of server/server.js, public/index.html,public/game.html. <!DOCTYPE html> <html> <title>QUIZ GAME</title ...

Having trouble reaching a public method within an object passed to the @Input field of an Angular component

My configurator object declaration is as follows. export class Config { constructor(public index: number, public junk: string[] = []) { } public count() : number { return this.junk.length; } } After declaring it, I pass it into the input decorated fi ...