Incorporating external function from script into Vue component

Currently, I am attempting to retrieve an external JavaScript file that contains a useful helper function which I want to implement in my Vue component. My goal is to make use of resources like and https://www.npmjs.com/package/vue-plugin-load-script. This endeavor is inspired by a helpful article that can be found at: https://www.sitepoint.com/geo-location-2-lines-javascript/

The main objective here is to access the city location of the current user for a weather application. In case there are no results, I would like to default to a predetermined city. The specific function within the external script that interests me is function geoplugin_city(), which provides the string representation of the current city, such as "Sydney".

My Vue component contains the following code snippet:

  mounted () {
    // Retrieve the script
    this.$loadScript("http://www.geoplugin.net/javascript.gp")
      .then(() => {
        // Utilize the script
        var city = geoplugin_city();
        this.getWeather(city); // --> execute my custom weather function using the city obtained from the script file
      })
      .catch(() => {
        // Failed to fetch the script
        this.getWeather("Sydney"); // --> execute my custom weather function with the predetermined city
      });
  }

Any assistance provided would be greatly appreciated! :)

Answer №1

Combining multiple solutions found here, experiment with injecting the script into the document and specifying its source URL.

  let newScript = document.createElement('script')
  newScript.async = true
  newScript.setAttribute('src', 'http://www.geoplugin.net/javascript.gp')
  document.head.appendChild(newScript)
  newScript.onload = () => {
    let city = geoplugin_city()
    this.getWeather(city)
  }
  newScript.onerror = error => {
    this.getWeather("Sydney")
  }

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

What is the importance of having Express in the frontend?

As someone who is relatively new to the world of JavaScript and web applications, I recently came across an Express web application project that contained a public directory, client directory, and server directory. This has raised some questions for me. I ...

What is the best approach for informing Vue about the location of my backend when accessing it through a network IP rather than localhost?

I have a Vue setup on localhost:8080 as a single-page application, and a Laravel backend running on localhost:80 as a REST API. Everything works perfectly fine on my computer. However, when I try to access my localhost web app on my phone using the networ ...

Envelop a HTML element within another HTML element with the help of jQuery

Unique link Here is some sample HTML: <div><img src="http://i.imgur.com/4pB78ee.png"/></div> I am looking to use jQuery to wrap the img tag with an a tag, like this: $(function() { var a = '<a href="http://i.imgur.com/4pB78e ...

The request for data:image/png;base64,{{image}} could not be processed due to an invalid URL

I am facing an issue with converting image data that I receive from the server using Angular.js for use in ionic-framework. Here is the code snippet I have been working with: $http.post(link, { token: token, reservationCode: reservatio ...

Make sure to choose the radio button that corresponds to the desired title value, as this will be automatically added to the input text

Visit this link for a live example. <div class='liveExample'> <input type="radio" name="gender" value="Mr." checked>Mr. <input type="radio" name="gender" value="Mrs.">Mrs. <p>First name: <input data-bind=&ap ...

Is it possible to alter the HTML structure using JavaScript?

Looking to shift the positions of 2 divs using JavaScript DOM manipulation, all without altering the HTML. <div class="div1"> this should move downwards</div> <div class="div2"> while this should move upwards</div&g ...

Vue's very own Vuex library

I created a Vue application using vue-cli-service as a library. "bundle": "vue-cli-service build --target lib --name search_widget \"src/components/index.js\"" This generates umd.js files that can be published to npm and imported into other Vue ...

Multiple minute delays are causing issues for the Cron server due to the use of setTimeout()

I have an active 'cron' server that is responsible for executing timed commands scheduled in the future. This server is dedicated solely to this task. On my personal laptop, everything runs smoothly and functions are executed on time. However, ...

Conceal an item upon deletion using the this.$http.delete() method

I'm trying to implement a feature on my VueJS frontend website where each deleted item is automatically hidden. In my store.js file, I have a property called eventIsActive which is initially set to true: export const store = new Vuex.Store({ state ...

Updating the organization of the models directory in Loopback

I am looking to update the structure of the models folder. As per the documentation, I can make changes to the json config file which is typically set up like this: { "_meta": { "sources": [ "loopback/common/models/**/*", "loopback/serve ...

Obtaining the 3D point coordinates from UV coordinates on a 3D plane object using Three.js

I am in the process of creating basic data visualizations using Three.js as my tool of choice. I have a series of PlaneGeometry meshes to which I am applying a transparent texture dynamically generated with red squares drawn at varying opacity levels. My g ...

When implementing the Dropdown Picker, it is important to avoid nesting VirtualizedLists inside plain ScrollViews for optimal

Currently, I am utilizing the RN library react-native-dropdown-picker. However, when I enclose this component within a ScrollView, it triggers a warning: "VirtualizedLists should never be nested inside plain ScrollViews with the same orientation because ...

What are the steps for utilizing JSON data retrieved from an ajax response?

After successfully making an ajax request and receiving JSON data, I am struggling with how to use it effectively. The response I am getting looks like this: [{ "id": "5", "reviewID": "2389", "serviceID": "50707", "title": "well d ...

An example of text that includes a link using ES6 template strings

My goal is to display the message "I read and agree to the privacy policy.privacy policy." where the 'privacy policy' part is a clickable link. I attempted the following code but it resulted in "I read and agree to the [object object]." const p ...

What is the best way to display JSON file results when clicking a button using Vue?

Once again, it's me! Check out my latest project here I am looking to retrieve data from a json file by inputting the necessary details and clicking on the button. For instance, let's say we want to find job listings for developers in Istanbul ...

Verifying the "select" dropdown option prior to final submission

My website features multiple select dropdowns that require validation before submission. For instance, there may be a situation where seven select dropdowns are present as described below. My desired validation criteria is: If there are 5 or more "sel ...

Clear Dropdown Selections prior to Submitting

When trying to change the value of the first dropdown list and reset the second dropdown before submission, I encountered an issue where the second dropdown still retains its previous selection upon submission. There is no submit button as the form is subm ...

Guide on converting the <br> tag within a string to an HTML tag in VUE.js

When working with Vue.js, I often use {{}} to display my data on the HTML page. However, I recently encountered a situation where my data includes a string with tags that I would like to be rendered as actual HTML tags when displayed. data(){ return ...

Incorporate a dynamic fading effect for text and images using JQuery

I successfully implemented a Crossfade effect using Jquery: function doAnimationLoop(o, n, t, i, a) { fadeInOut(o, n, t, i, function() { setTimeout(function() { doAnimationLoop(o, n, t, i, a) }, a) ...

Surprising non-synchronous operation within the computed property "vue/no-async-in-computed-properties" in Vue3

I am currently working on a Vue3 project and encountering an error when running it. Below is the complete code snippet that I am using. Can anyone assist me in resolving this issue? Thank you in advance. <script> import axios from 'axios'; ...