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

How can jQuery determine the amount of line breaks within a div element?

My div wrap size is a percentage of the screen width, containing multiple .item divs that break into new lines as the window size decreases. I attempted to calculate the total number of boxes that could fit based on their widths compared to the container ...

Executing PHP code on button click in HTMLThe process of running a PHP script when

I am currently working on a project that involves detecting facial expressions using Python. However, I need to pass an image to this code through PHP. The PHP code provided below saves the image in a directory. How can I trigger this code using an HTML ...

Ways to access information received from AngularJS in a different Javascript file

I am currently using Angular to retrieve output from a controller and display it using ng-bind. However, I have another separate JavaScript file that needs to utilize a value returned from Angular. In the example code provided below, the TestAppCtrl is ca ...

Tips for preventing repetition of code in multiple entry points in Rollup

My goal is to use rollup to process a group of input files and generate multiple output files in the dist directory that all have some common code shared between them. Below is my current rollup configuration: import path from 'path'; import pat ...

The bidirectional bindings within the component are malfunctioning

I just started learning Angular and I'm currently working on a small project. After following tutorials on two-way bindings, I attempted to implement it in my project. However, when I try to set values in the HTML for my component, it doesn't see ...

Is there a way to ajax just specific HTML table rows instead of transmitting all the form inputs?

For weeks, I've been struggling to use AJAX POST with a JSP script to update my HTML table rows without success. Can anyone provide guidance on this? Below is what I have attempted so far. window.addEventListener("DOMContentLoaded", function () { ...

Ensure exclusive access to variables for sequential updates in jQuery or JavaScript

I am currently developing a series of small functions in jQuery aimed at tracking how long it takes for a user to complete a form. The form consists of various input types and 'continue' buttons located within the form itself. Below are some sa ...

Ways to access information and functions from another component

Creating a timer dashboard where alarms can change the background color of the timer. Looking to display the timer on a different page with the set background color from the dashboard, but struggling to pass data between components successfully. http ...

Leveraging Vue.js to preload data with client-side rendering

When it comes to server-side rendering in Vue, like with Nuxt, the process involves grabbing data using the serverPrefetch() function and rendering content on the server side. This allows for the request to return data to the user only after the initial do ...

Preventing values from being overridden when setting them in a loop using Vue JS and Firebase

After pulling data from Firebase and updating the roomName value in a loop, I'm finding that the updated value is not recognized outside of the loop. Can anyone offer assistance with this issue? export default { name: "Chat", compone ...

Ensuring the Line Breaks in CSS and JavaScript to Easily Modify the Style

Is there a way to determine when a line will break so I can apply different styles? The design team needs 3 buttons in a grid (3 columns) with specific sizes. They want buttons with content that breaks onto the next line to have a border-radius of 13px, w ...

Transforming JSON format to another JSON format using AngularJS

I am in the process of setting up a questionnaire using angularjs. I have an array of responses that looks like the following, and I need to convert this object array into JSON format. How do I go about converting an object array into JSON format? ...

Using an AJAX self-invoked function to update Vue data

I have been attempting to utilize a self-invoked function for an ajax call. However, I am facing issues when trying to use the response to populate a data property within Vue. This is the code I have implemented: //Ajax call to service var getData = (fun ...

The error message "Uncaught TypeError: Cannot read property '0' of undefined" is triggered when using toDataURL

Recently diving into the world of JavaScript and facing a perplexing error. I must be overlooking some fundamental concept... apologies in advance. Here is the issue at hand. In my HTML file, this snippet of code is present: <div> <script type= ...

Automatically adjust div dimensions as window is resized

I am attempting to dynamically set a height in pixels for my container when its size changes. I have managed to display the size as text, which successfully updates when the container is resized. However, the height attribute on my container does not updat ...

What is the best way to fix multiple dropdown menus opening simultaneously in Vue.js?

I am working on an application that generates todo lists for tasks. These lists can be edited and deleted. I am trying to implement a dropdown menu in each list to provide options for updating or deleting the list individually. However, when I click on the ...

Tips for iterating through a nested object in JavaScript with the forEach method

Here is my answer to the query. In this snippet, results represents a freshly initialized array. The object address nests within the user object. response.data.forEach(user => { results.push({ id: user.id, name: user.n ...

Encountered an error during module parsing: An unexpected character '@' was found at position 1 in the code related to vuejs, vuetify, and vu

Encountering an issue when trying to add/integrate Vuetify, such as importing it with the line 'import Vuetify from 'vuetify/lib' Vue.use(Vuetify)' in main.js Error: ERROR in ./node_modules/vuetify/src/stylus/components/_grid.styl Mod ...

The jQuery bookmarklet in the djangobyexample book is completely unresponsive

As I work my way through Django By Example, I came across a chapter where a jQuery bookmarklet is created within a Django app. This allows users to easily save jpg images from websites into their user profile area within the Django app. Although the tutor ...

Issue with Material UI: Unable to utilize import statement outside of a module due to Select dependency

Hello there! Here is my query: I am currently working on a project using NextJS + React with node. Everything seems to be running smoothly, except for one issue I encounter when reloading a page with a Select component from Material UI. The relevant code ...