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

Are items placed into an array passed by reference or by value?

When working with custom Objects in an Angular context, I define two objects "a" and "b" using an interface. These are created as class attributes along with an empty array of these objects. public a: CustomObj; public b: CustomObj; public array: ...

Utilize an array value as a parameter for getStaticProps within Next.js

Currently, I am fetching my Youtube playlist using a fetch request and utilizing getStaticProps(). However, I am encountering an issue where my playlist is dependent on the result of an array of objects. export async function getStaticProps(){ const MY_P ...

disabling a submit button

I am new to coding and need help disabling a button on document load. Can someone assist me with this? Here is my current code snippet: $(document).ready(function() { setTimeout("check_user()", 250); }); Your guidance is greatly appreciated! ...

AngularJS seems to be ignoring CSS styles when displaying list items in the ng-repeat loop

After coming across a tutorial on creating round circles connected by a line in CSS, I decided to implement it myself. Interestingly, everything worked perfectly fine when I tested it with static HTML. However, when I tried to make it dynamic using Angular ...

Calculate the total price using jQuery

I’m a beginner in JavaScript and I’ve hit a roadblock. I have a plus and minus button that adds up product quantities, but I need the total price to reflect this as well. Some products can only be purchased in multiples of 2, 5 or 10. Here is the HTML ...

The themes showcased in the Bespoke.js documentation and demo exhibit unique designs

Recently, I stumbled upon an incredible HTML5 framework for presentations. For more information, you can check out the documentation here. You can also view a demo of the framework by visiting this link. However, I was disappointed to find that the caro ...

What steps should I follow to ensure that the message "Read It" is logged to the console before "Ex It"?

app.get('/', async (req, res) => { await fs.readFile('./views/website/index.html', 'utf8', (err, d) => { data = d console.log("Successfully read the file") // console.log(data) ...

Is there a way to align the navbar to the center in bootstrap vue?

I'm trying to center my navbar component, but I can't seem to figure it out. This is my first time attempting this and everything else looks good except for this issue. <template> <div class="container"> <header> &l ...

The error in ReactJS is coming from the render method of the `News` component

While working with React JS, I encountered an error when trying to run a particular code snippet. The error message displayed was: "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got ...

Data is not loaded until after the HTML for the Nuxt page has been

My issue is that I have a dynamic page where product details are loaded, but the html code loads before the data. This results in errors when trying to use static elements like images because the "product" object does not exist. To address this problem, I ...

Trigger a function in AngularJS when a div is scrolled to within a specific number of pixels from the bottom of the screen

I am experimenting with the AngularJS infinite-scroll directive. Below is the code snippet: angular.module('infiniteScroll', []) .directive('infiniteScroll', [ "$window", function ($window) { return { link:funct ...

Clicking on buttons in the header does not lead to the intended section when scrolling

I have just completed a website project for a Udemy course, following all the instructions provided. However, I am facing an issue with the functionality of two buttons on my site. I want these buttons to scroll to specific sections when clicked. The "I&ap ...

What is the process for extracting information from a middleware within a Next.js framework?

I have been working on developing an authentication system using JWT in Next.js. In order to achieve this, I created a middleware that can validate the JWT token and establish an authentication process as shown below: export default function middleware(req ...

A guide on making Rest Requests with VueJs 2 and Symfony 3

Trying to send a PATCH request for an event using VueJs 2, here is the code snippet: // Link and body are defined correctly this.$http.patch(linkUrl, this.baseTerms, {someKey:'any value'}).then(response => { console.log(response.body) ...

The characteristics that define an object as a writable stream in nodejs

Lately, I've been delving into the world of express and mongoose with nodejs. Interestingly, I have stumbled upon some functionality that seems to work in unexpected ways. In my exploration, I noticed that when I create an aggregation query in mongoos ...

What is the best way to format or delete text enclosed in quotation marks within an anchor tag using CSS or JavaScript?

I have encountered an issue with a dynamically generated login form. When I select the 'Forgot Password' option, a new 'Back to Login' message appears along with a separating '|' line. Removing this line is proving challenging ...

Eslint highlighting the initial function declaration within a Vue script

I'm currently creating a Vue file using a Typescript script, and encountering an unusual Eslint "error." The issue arises on line 15 with this specific complaint: Parsing error: Unexpected token, expected "," Interestingly, this error only occurs wi ...

Is there a way to delay rendering the html until all the content has been fully downloaded?

Whenever I visit my webpage, I notice that the content starts loading without the animation applied to it. It seems like the CSS hasn't finished downloading yet. To solve this issue, I added a preloading bar overlay to signal that the content is still ...

Creating a user-friendly form with validation in a Vue application using Vuetify.js

I am in the process of incorporating a contact form with basic validation on a Vue.js website using an example from Vuetify.js. Being new to this, I'm unsure about how to implement it within a Vue component. My goal is to have simple client-side form ...

Utilize jQuery to dynamically assign classes to list items within a unordered list based on the length of an array

HTML: <ul class="tickboxes"> <li><i class="fa fa-check"></i></li> <li><i class="fa fa-check"></i></li> <li><i class="fa fa-check"></i>< ...