Loading external scripts prior to component loading in Vue.js

Within my Vue project, I have the need to fetch a script from a server location (e.g. https://myurl.com/API.js). This script contains a variable that I intend to utilize within my Vue component/view. The issue arises when I attempt to load this script using the loadScript module:

import Vue from 'vue'
import LoadScript from 'vue-plugin-load-script';

Vue.use(LoadScript);
Vue.loadScript('https://quvia.cz:4443/portalAPI.js')

The script ends up loading after the Vue component, leading to situations where trying to

console.log(externalScriptVariable)
results in an undefined value. As a quick workaround, using setTimeout for 1 second allows the variable to be output successfully.

Is there any way in Vue.js to effectively "await" the script loading process, ensuring it loads before all other Vue components?

Answer №1

To utilize asynchronous functionality in Vue, you have two options:

import Vue from 'vue'
import LoadScript from 'vue-plugin-load-script';

Vue.use(LoadScript);

(async function() {
  await Vue.loadScript('https://quvia.cz:4443/portalAPI.js');
  // perform additional actions once the script is loaded
})(); 

You can also use promises with then:

import Vue from 'vue'
import LoadScript from 'vue-plugin-load-script';

Vue.use(LoadScript);

Vue.loadScript('https://quvia.cz:4443/portalAPI.js').then(() => {
  // handle other tasks after the script loads successfully
})
.catch(() => {
  // catch any errors that may occur during loading
});

Answer №2

In my experience, I was able to resolve the issues by utilizing the "window" scope. Additionally, when needing to access a Vue element within the "onload" function, it was necessary to create a new variable for the current instance of "this".

<script>
import { mapActions } from "vuex";
export default {
      name: "Payment",
      methods: {
        ...mapActions(["aVueAction"])
      },
      created() {
            let paywayScript = document.createElement("script");
            let self = this;
            paywayScript.onload = () => {
              // calling Vuex action
              self.aVueAction();
              // calling script function
              window.payway.aScriptFunction();
            };
            
            paywayScript.setAttribute(
              "src",
              "https://api.payway.com.au/rest/v1/payway.js"
            );
            document.body.appendChild(paywayScript);
      }
};
</script>

This code was implemented in Vue 2.6.

Answer №3

If you want to dynamically load a script in Vue, consider using the beforeCreate() lifecycle hook provided by Vue.

import LoadScript from 'vue-plugin-load-script';

export default {
  name: "App",
  beforeCreate() {
    LoadScript('https://quvia.cz:4443/portalAPI.js')
  }
};

There are other lifecycles available in Vue that may also be suitable for your needs - you can explore them here: https://v2.vuejs.org/v2/guide/instance.html

Additionally, calling the LoadScript function in the main.js file ensures it is executed before any components are loaded.

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

Looking for a quick guide on creating a basic RESTful service using Express.js, Node.js, and Mongoose?

As a newcomer to nodejs and mongoDB, I've been searching high and low on the internet for a tutorial that combines express with node and mongoose. What I'm specifically looking for is how to use express's route feature to handle requests and ...

Experiencing pagination problems with Vue / Laravel framework

Trying to implement pagination for fetched data in a Vue project, but encountering an issue: New Question Error encountered during rendering: "TypeError: this.estates.filter is not a function" Am I overlooking something here? Pagination.vue ...

Delay the occurrence of a hover effect until the previous effect has finished executing

As I hover over an element, the desired animation is displayed while hiding other elements on the page. The challenge I'm encountering is that if I quickly hover over many divs, the animations queue up and hide the divs sequentially. I want only one ...

What steps can be taken to adjust a module required in Node.js prior to initiating the build process?

Module A.js (standard NPM package): module.exports = { ... const wsUrl = `ws://${customHostname}:${customPort}/sockjs-node/websocket`; ... }; Module B.js: const a = require('A'); Is there a way to substitute ${customHostname} & ${cu ...

Customizing Pie Legends in Echart Configuration

I am trying to find a way to present pie chart legends along with their values in a unique format. I have attached an image for reference. Despite my efforts, I haven't been able to figure out how to achieve this specific display. If you take a look a ...

Unable to physically tap on the checkbox input, though able to perceive the value it holds

When running my protractor test, I encountered an issue with the following statement: await element(by.model('publishCtrl.isPublishedInAllRegions')).click(); The test failed and returned an error message stating "ElementNotVisibleError: element ...

Tips for replacing the values obtained during parsing an XML document

I am working with an XML file that contains category and product information. Here is a snippet of the XML data: <categories> <category id="2" name="Pepsi" > <products> <product id="858" name="7UP" price="24.4900" /> ...

How a JavaScript function handles the scope of a for loop index

Here's some Javascript code I'm working with: func1() { for(i = 2; i < 5; i ++) { console.log(i); func2(i); } } func2(x) { for(i = 100; i < 200; i ++) { do something } } I've noticed that when runni ...

Troubles encountered when cascading val(), text(), and data()

Here is my JavaScript/jQuery code: $select.append($("<option />") .val(this.id) .text(this.text) .data('name', this.name) .data('isstorage', this.isstorage)); Although it successfully assigns values to t ...

How can JavaScript be utilized to disable the use of the spacebar?

I have implemented a live search feature on the website I'm working on. Currently, the search function queries the MySql database as soon as the first character is entered and updates the results with each subsequent character input. However, I'v ...

When trying to access the key value of a dynamically generated object, it returns as undefined

I am facing a challenge with my student object structure... { Freshmen: [{id: 3}, {id: 5}], Sophomores: [{id: 2}, {id: 6}], Juniors: [{id: 1}, {id: 8}], Seniors: [{id: 9}, {id: 4}, {id: 7}] } My goal is to retrieve full student objects from the d ...

Retrieving time zone using offset with javascript

I am looking for a way to schedule time-based events on my server operating in UTC time. For the user interface, I need to input 2 parameters: The local time when the scheduled event should trigger The timezone offset Instead of displaying timezone n ...

Steps to create a toggle feature for the FAQ accordion

I am currently working on creating an interactive FAQ accordion with specific features in mind: 1- Only one question and answer visible at a time (I have achieved this) 2- When toggling the open question, it should close automatically (having trouble with ...

Change the left position of the sliding menu in real-time

I am currently designing a website with a sliding menu feature. By default, the menu is set to -370px on the left, displaying only the "MENU" text initially. When a user hovers over the menu, it expands to the right, allowing them to select different menu ...

What is the reason for not receiving a JSON object in the response from my personal node.js/express server?

-- Exploring a New Challenge -- I am currently working on creating an e-form signup for a client as part of our business marketing strategy service. The form design is complete and looks excellent. Now, I need to connect it to the existing API that our bu ...

Employing jQuery to redirect to a different URL when a button is clicked

I've been experimenting with a project that involves both JQuery and AJAX. One of the features I have added is JQuery autofill. Here is the code snippet for the form: <form class="form-horizontal"> <div class="form-group"> < ...

Scrolling up or down in an HTML webpage using a script

Seeking a code snippet for my website that will allow me to achieve the following functionality: Upon clicking on text_head1, a list of lines should scroll down. Subsequently, when I click on text_head2, the previous list should scroll up while the new l ...

Enabling CORs headers in Express continues to lead to errors

I have implemented the CORS code provided on http://enable-cors.org/ for express into my index.js file. /*these first five line direct from http://enable-cors.org/.com*/ app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); ...

Test the file upload functionality of a Node Js application by simulating the process using Chai

My API testing involves receiving a file as input. I have successfully used the attach() function for this purpose. To cover all scenarios, I anticipate using around 20 different input files. Rather than storing these 20 files individually, my idea is to c ...

Experience the simplistic magic of the Vue.js/Vuefire/Firebase app world, though it struggles with reading values

Transitioning to Vue.js from SQL programming has been a bit of a challenge, but I'm getting there. Currently, I am using vuefire according to the specifications and even manually inserting the correct key from my Firebase database with one record and ...