Anticipating the arrival of an external JavaScript file in the child component

I am facing an issue with my parent component that dynamically loads an external js file (similar to what is explained here).

The child component needs a variable inside the js file, but it throws an error every time the page is loaded because the child component renders before the external js file is fully loaded. How can I prevent this from happening?

//in parent component
app = new Vue({
    el: '#app',
    created() {
        this.loadJsFile('assets/js/extra.js')
    },
    methods: {
        
        loadJsFile(src) {
            var script = document.createElement('script');
            script.src = src;

            let head = document.getElementsByTagName('head')[0];
            head.appendChild(script);
        },

In extra.js:

var extra = { users:[{id:1, name:'foo'}], images:[...] }

Child component:

data() {
    return {
        users:[],
     }
},

created(){
    this.users = extra.users
},

causing the error:

[Vue warn]: Error in created hook: "ReferenceError: extra is not defined"

Answer №1

Explore some solutions tailored to your situation:

1. Dynamically insert the <script> tag

In the parent component:

<ChildComponent :extra="users"></ChildComponent>

...
mounted() {
  this.loadJsFile('assets/js/extra.js').then(() => {
    if (window.extra) {
      this.users = extra.users
    }
  })
}

// ...

loadJsFile(src) {
  return new Promise((resolve, reject) => {
    let script = document.createElement('script');
    script.onload = () => {
      resolve();
    };
    script.onerror = () => {
      reject();
    };
    script.src = src;

    let head = document.getElementsByTagName('head')[0];
    head.appendChild(script);
  });
}

In the child component:

...
   props: {
      extra: Array
    },
   data() {
    return {
        users:[],
     }
   },
   created(){
     this.users = this.extra.users
   },

2. Include <script> tag in the index.html file:

Simply append

<script src="static/js/extra.js"></script>
at the bottom of the index.html file to globally access the extra variable.

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

Quick + Vue Router - Lazy Loading Modules

For my personal project, I am using Vite alongside Vue 3 and have integrated vue-router@4 for managing routes. Since all of my modules share the same set of routes, I created a helper function: import { RouteRecordRaw } from 'vue-router' import p ...

JQuery loader & amazing animations

I have implemented the wow.js plugin along with a jQuery preload tutorial from here. Although the preloader works fine, I am facing an issue where the animation by wow.js starts before all the elements on the page are preloaded. I am looking to modify my ...

Will "Access-Control-Allow-Origin" provide protection if someone directs their domain to my server?

It seems I may have misinterpreted the full implementation of CORS on my server. Looking at this screenshot of a request made through Chrome. https://i.sstatic.net/9F1tE.png We can observe that we are accessing the site shakh.photography, where the requ ...

Why does the Hamburger Menu shift my website's logo when it opens?

I'm in the process of implementing a hamburger menu on my website. My attempts have involved adjusting the positioning of both the #logo and .topnav elements. Code Snippet source function myFunction() { var x = document.getElementById("myTopn ...

Using references to pass variables in JavaScript - passing variables to an external test in Mocha

When dealing with primitive datatypes in JavaScript, passing by reference doesn't work. One common workaround is to wrap them in an object. However, what happens if a variable starts as null and then gets reassigned as an Object before being passed to ...

Storing an image or video file to the disk of a NodeJS server and creating a reference in MongoDB

Seeking advice on the optimal method to store an image or video file on a NodeJS server and link it to MongoDB. Additionally, I need to enable streaming for the videos. Any recommendations would be greatly appreciated. Thank you! ...

Setting up HMR for a Vue.js app can be a bit tricky, especially when trying to run it locally

1. The Caddy version I am using (caddy -version): v2.0.0-beta.13 h1:QL0JAepFvLVtOatABqniuDRQ4HmtvWuuSWZW24qVVtk= 2. How I execute Caddy: a. Environment details: I have the caddy server static binary running on macOS Mojave - 10.14.6, and added the bina ...

Comparing parameters between two functions in Javascript: a step-by-step guide

I am currently working on solving this problem: var name; var totalScore; var gamesPlayed; var player; var score; // Creating the game player object function makeGamePlayer(name, totalScore, ga ...

Using Express and Node.js to implement the Google Maps API

Currently working on creating a simple web application using the Google Maps API with express/node. At the moment, I have three main files that make up my project: server.js const express = require('express'); const bodyParser = require(' ...

Sophisticated method for arranging three integers in javascript in descending order, followed by analyzing their relative distances

In developing an interactive infographic, I am working with three integers assigned to variables, each ranging from 0 to 50000. These numbers often have values that are close to each other, and I am looking for a way to identify when either 2, all 3, or no ...

Move through different screens using React JS

Can anyone help me with this issue I'm facing in React Js? I am trying to implement a button that changes to another screen when clicked, but I keep getting an error message: TypeError: Cannot read property 'push' of undefined. I have tried ...

Utilize a single JWT token across various Vue.js applications

Can JWT tokens be shared between several Vue.js applications that are hosted on the same domain? For instance, having a primary app for user login and transactions, and a reviews app in a subdirectory where users can only leave reviews. ...

How can I move a nested child component out of an ancestor element with overflow set to hidden?

I'm facing an issue with a sliding carousel where the overflow-x property is set to hidden. The carousel displays 4 items at a time, and each item contains a button that triggers a pop-out menu positioned relative to its parent item. The problem arise ...

Why does jQuery val() function fail to clear readonly input date in Firefox but succeed in Chrome?

When using JQuery.val(''), I noticed a difference in behavior between Firefox and Chrome. You can see the issue demonstrated in this jsfiddle: https://jsfiddle.net/mdqfbj/d4eovkg8/3/ A JS function triggered by a radio button is supposed to clea ...

What are the specific files I should modify for HTML/CSS in my Ruby application?

My application was initially created with an introduction from: http://guides.rubyonrails.org/getting_started.html I am now looking to add some color and style through CSS. I have located the JavaScript and CSS files, but I am unsure which file is respons ...

The specialized element encountered an issue with mapping

For a while now, I've been trying to create my own custom component but it's not working as expected. The interaction seems fine, but for some reason, it only renders the last item in the arrays. export default class MyComponent extends Comp ...

"Enhance Your Design with Hovering CSS Backgrounds

Seeking assistance with changing the background image on span hover. If anyone can assist, I have included the complete code for the website below. Take a look at the full website code here: Pastebin CSS Pastebin JavaScript ...

Debugging Node.js Routes in Visual Studio Code: A Step-by-Step Guide

My application is structured as follows: server.js router routes emails.js index.js In my index.js file, I define the route like this: module.exports = function (app) { app.use('/emails', require('./routes/emails& ...

Modify the navbar background color in bootstrap-vuejs

As per the information provided in the documentation, the instructions for setting styles for the navigation bar are as follows: <b-navbar toggleable="lg" type="dark" variant="info"> <!-- Or --> <b-navbar toggleable="lg" type="dark" variant ...

The column headers are not being shown in Jquery datatables

This particular question is related to the thread found here. Nevertheless, my situation differs slightly. I am looking to implement the same datatables example from the aforementioned question, which can be accessed here. In that example, you must provide ...