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

Deactivate a Specific Popup for a Specific Page

In my project, I have a file called modal.php that contains two modal windows: Login Modal Feedback Modal The Login Modal automatically pops up every 5 seconds for users who are not logged in. The Feedback Modal opens when clicked. On my website, I hav ...

An issue arose in ReactJS when trying to utilize the GraphQL API

Struggling to incorporate the graphql API into a react js application. Uncertain if this approach is correct. import React, { Component } from 'react' import "./styles.css"; import axios from 'axios'; const appBaseUrl = axios.create({ ...

Fancybox's Exciting Tandem Events

I am currently experiencing an issue with my popup ajax contact form as it only has one close event... The AJAX contact form I have consists of two buttons, SEND and CANCEL. When I click the SEND button, the Sweet Alert confirmation message displays ...

Can ReactJS and jQuery be used together or are they mutually exclusive?

As a beginner in the world of ReactJS, I am intrigued by how this library essentially handles all DOM node rendering without any need for interference from other libraries like jQuery. However, this does pose a challenge as many convenient jQuery plugins ...

Acquiring a fresh scope in Angular via a different component

In my project, I am developing an app using a component-based approach with Angular 1.5.5. As part of this development, I am utilizing d3js to create some elements with the class .floating-node. For each of these nodes, I am creating a new $scope and appe ...

Request for removal in Express.js

Currently in the process of developing a MERN-stack app, but encountering issues with the delete request function. Here is the relevant code snippet: Upon attempting to send a delete request via Postman, an error message is displayed. I have researched ...

Tips for removing the default hover and click effects from a Material-UI CardActionArea

Check out the card sample with a lizard photo on https://material-ui.com/components/cards. When you hover over the cardActionArea, it will get darker or lighter based on the theme. Clicking on the card will make the picture change its brightness relative ...

Expand the video comparison slider to occupy the entire width and height

I am striving to develop a video comparison slider that fills the height and width of the viewport, inspired by the techniques discussed in this informative article: Article Despite my efforts, I have not been successful in achieving this effect so far a ...

The ins and outs of implementing i18n on an Angular component library

My custom component library is not functioning properly with i18n within my module // To enable Ahead-of-Time compilation, a function must be exported for factories export function HttpLoaderFactory(http: HttpClient) { return new TranslateHttpLoader(ht ...

Issue with nextjs not returning the updated object correctly

I'm currently developing a nextjs app that incorporates authentication. There are two key functions that I execute on each page load. The first function checks for the existence of jwt cookies and then calls another function to validate the tokens if ...

Bringing life to web pages through captivating animations when showing and hiding div elements, utilizing the power

After extensive research on various online platforms, including stackoverflow, I unfortunately couldn't find a suitable solution to my problem. However, with the invaluable assistance of you all, I managed to successfully implement a code for my proje ...

The class is failing to be applied to the parent div that holds an id starting with the letter x

I have been attempting to assign a class to the parent container when the child element has the 'hidden' class. If not, then a different class should be added. function tagMissions() { if ($('span[id^="mission_participant_new"]').h ...

Pondering in AngularJS - what is the best way to alter the DOM during an AJAX call?

I'm completely new to AngularJS and trying to transition from a jQuery background. After reading through "Thinking in AngularJS if I have a jQuery background?" on Stack Overflow, I understand the concept but am struggling to implement it without depen ...

Preventing input in one textbox if another textbox has a filled value in HTML

Apologies for asking this question, but is there a way to disable one text box if another text box has a value? I've attempted using the following code, but it doesn't seem to work. Sorry for the inexperienced inquiry T_T function disableTextbox ...

Utilizing HTML and Javascript for streaming audio and recording voice

Working on a new project that involves streaming audio files (mp3) and recording voice messages. Initially considered using Flash, but the challenge is making the website iPhone-friendly as per the client's request. Is there a technology available th ...

The interaction between a JavaScript function call and C# is not functioning properly

Attempting to invoke the JavaScript function from CodeBehind ( C# ) : function scrollToBottom() { window.scrollTo(0, document.body.scrollHeight); } The function successfully executes when directly called from my asp.net application. However, ...

The functionality of AC_FL_RunContent is failing after an UpdatePanel postback

In the code for the repeater item, I have a JavaScript function that calls AC_FL_RunContent to display a flash file when a link within the repeater item is clicked. The datasource I am using displays the first page of video links with five items per page, ...

The challenges of updating AngularJS partial templates and handling refresh in 2-way binding

I've encountered an issue with a partial template that's loaded outside of my ng-view, complete with its own controller. Here's a breakdown. Basic template layout <html ng-app="myApp"> ... <div ng-include src="'myPartia ...

React-Native error message: Promise rejection unhandled - React child cannot be an object

I am experiencing an issue with rendering a list from an array of objects that have the structure provided below. While I have successfully handled the promise and set the data to the state, I keep encountering an error specifically with this array. The da ...

What is the best approach to structure a React project in which a component's rendering changes with each instance?

I am facing a challenge with rendering a component that relies on multiple AJAX calls to complete. These AJAX responses return different data each time, and I want to implement a button that will trigger the re-rendering of this random component every time ...