-1

I'm trying to access external js -script containing a helper function to use in my Vue component. I'm trying to utilize https://www.geoplugin.com/webservices/javascript and https://www.npmjs.com/package/vue-plugin-load-script, inspired by this article: https://www.sitepoint.com/geo-location-2-lines-javascript/

I'm trying to access a city location of current user for my weather app, and if no result, use a predetermined city. The function I'm intrested in the external script file is function geoplugin_city() which returns a string of current city, for example "Sydney".

My block of code inside my Vue component is:

  mounted () {
    // Access script
    this.$loadScript("http://www.geoplugin.net/javascript.gp")
      .then(() => {
        // Do something with script
        var city = geoplugin_city()
        this.getWeather(city) // --> run my own weather function with city from script file
      })
      .catch(() => {
        // Failed to fetch script
        this.getWeather("Sydney") // --> run my own weather function with predetermined city
      });
  }

I would appreciate any help! :)

Tuuchen
  • 97
  • 4
  • 10

1 Answers1

1

Amalgamating a few answers here, try adding the script to the dom and set its src property to your script's URL.

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