Trouble with the onload function in onMounted vue3

For my vue3 component, I need to load certain scripts. Here is what I am currently implementing:

<script setup>
import { onMounted } from 'vue'

function createElement (el, url, type) {
  const script = document.createElement(el)
  if (type) script.type = type
  script.src = url
  return script
}

onMounted(() => {
  const customScript = createElement('script', 'https://example.com/script.js', 'text/javascript')

  customScript.onload = () => {
    // Execute code once script is loaded
    console.log('Script loaded successfully!')
  }

  customScript.onerror = () => console.log('Error loading script')
})

</script>


The function createElement is used to dynamically generate any required element. However, I am facing an issue where the onload block is not triggering as expected after loading the script instance.

Answer №1

When you structure your code in this way, you are essentially invoking the 'onload' function within your 'createEl' function instead of utilizing the Neshan SDK as intended.

To address this issue, I recommend either initializing the Neshan SDK in a separate JavaScript file and then importing it into your Vue file, or including the script tag in your index.html file. It is important to remember that 'ol' is exported by the SDK as per Neshan documentation and an API key is necessary.

// Update: Neshan.vue file

export default {
  setup() {
  
    const neshan = window.ol;     // 'ol' sourced from index.html
    
    const map = new neshan.Map({
      target: 'map',
      key: 'YOUR_API_KEY'         // Obtain API key from developer.neshan.org
      maptype: 'neshan',
      poi: true,
      traffic: false
    })

    console.log(map)
    
    return {
      neshan,
      map
    };
  },
};
<!-- Included in index.html -->

   <link rel="stylesheet" type="text/css" href="https://static.neshan.org/sdk/openlayers/5.3.0/ol.css">
   <script type="text/javascript" src="https://static.neshan.org/sdk/openlayers/5.3.0/ol.js"></script>

The simplest solution may be to utilize the Neshan Vue3 package available on GitHub.

npm i vue3-neshan-map-openlayers

Answer №2

A breakthrough moment! I finally cracked the code on how to make the loaded script usable. All it took was a single line added to the createEl function:

function createEl (el, url, type) {
  const script = document.createElement(el)
  if (type) script.type = type
  script.src = url
  **document.body.appendChild(script)**
  return script
} 

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 proper way to utilize the "Long" type when declaring a schema in MongoDB?

Forgive my ignorance, but I am trying to achieve something like this: var mongoose = require('mongoose'); var Long = require("long"); var UserSchema = new mongoose.Schema({ id: Long(), name: String, completed: Long(), ...

Is there a way to format wrapped lines with indentation in an unordered list?

Is there a way to indent the wrapped lines of text in an unordered list? The current layout is not quite what I want, as shown in the first image below. Ideally, I would like it to look more like the second image. I attempted to use margin-left: 56px; and ...

Using Middleware in Node JS Routes for Paginating Data Tutorial

Recently delving into Node and Express, I found myself integrating a pagination feature into my API. Although I've made significant progress, I'm facing challenges after refactoring and converting pagination into a function. This is the current ...

What is the best way to highlight specific text in React components that is passed from an object?

This is the page HTML content where an object is created. A portion of the description needs to be emphasized: const agencyProps = { title: "Managed agency selection", paragraph: "Strengten your onboarding process", videoImage: { ...

Performing a jQuery ajax request by passing data obtained from iterating through elements

Is it possible to iterate through elements and send the element value within the data: {} parameter of $.ajax()? For example: $result = pg_query($connection, "select * from tbl_salary_deductions"); while($row = pg_fetch_assoc($result)) { ...

Tips for selecting the appropriate cssSelector value within the Chrome browser using the Developer Tools (F12) feature

What is the process for selecting a cssSelector() in Chrome Browser using Chrome Developer Tools? Could you provide an example for the given code snippet below? WebElement searchBox = driver.findElement(By.cssSelector("selector")); searchBox.click(); ...

Unable to access parameters from Pug template when using onclick event

I am facing an issue with my pug template test.pug. It contains a button that, when clicked, should call a function using parameters passed to the template from the rendering endpoint. Below is the structure of my template: doctype html html head tit ...

An issue with flickering in JavaScript tooltips on HTML5 canvas

I have encountered an issue with canvas tooltip in HTML5. Although everything appears to be functioning smoothly, when I calculate the canvas tooltip's position near the top right corner of the canvas (to ensure it remains within the canvas boundarie ...

Express/NodeJS encountering a CORS problem, causing services to be inaccessible in Internet Explorer

Currently, I am working on a REST-based service implemented in Express/NodeJS. The code includes CORS (Cross Origin Resource Sharing) implementation to allow services to be consumed from browsers like Chrome and Firefox. However, there seems to be an issue ...

Having difficulty accessing a PHP ajax post request

I've scoured every resource but can't seem to find a solution to this issue. I'm in the process of writing an ajax script, however, I am struggling to retrieve the correct value from the POST request. Here is the code I have so far: <t ...

Show information in a React Native element | Firebase

Just starting out with react native and struggling to display data in a component? You're not alone! I'm having trouble too and would love some guidance on how to destructure the data for display. Any tips? import React,{useState,useEffect} from ...

Creating a custom Vue.js component for specific table cells within a table row - here's how!

My challenge is having related and neighboring table columns grouped within the same component in Vue.js. However, I'm facing a limitation with the template system where only one tag can be directly placed inside <template>. Typically, this wrap ...

A method to implement an If Loop on a cube using Threejs in order to generate an interactive on-hover feature that enlarges the cube's size

Having just completed my first tutorial in threejs as a novice, I am now facing a challenge. I am trying to create a hover effect on a basic cube shape where it grows in size when the mouse pointer hovers over it and shrinks back to its original size when ...

Creating a Custom Alert Box in Javascript with Image Alignment

I have just finished creating a custom alert box using Javascript, complete with text and images. However, I am facing an issue with alignment. The output is not as expected. I am trying to display the correct mark and text on the same line. Can someone ...

What is the best way to store XHR data in a browser's cache?

I have been seeking a solution to locally cache an XHR request on my computer for future use. Whenever I visit an online shop, I often encounter a form in the order page that includes a field with XHR. After filling out this field, I have to submit the f ...

React App stalled due to continuously running function

In this section of my React app, the createBubbles function is functioning properly. However, I am encountering an issue where the entire app freezes when navigating to another page after visiting this one. The console displays the following errors and de ...

Tips for fading out two elements after completing a drag and drop action

Visit this Codepen for more examples - Codepen I have been developing a drag and drop feature in my application. Once the item is dropped, it transitions from red to green and fades out smoothly. The droppable element behind the draggable should also fad ...

Using jQuery to toggle the visibility of a group of radio buttons causes the div to quickly appear and disappear

My code is working perfectly as it shows up when needed and disappears when necessary. The concept behind this form is that the user can check a box, view more required form data related to the checked item, make those fields required, and then uncheck the ...

AngularJS is not properly clearing the datepicker

Upon submitting the form, I have managed to reset all input fields to blank except for the datepicker which still retains the previously selected date. How can I clear that as well? Snippet of HTML: <div> <form name="profileform" role="fo ...

Changing the slider based on the format of the price and user input value

Is there a specific place where I should use the .toFixed(2) method to ensure fixed formatting for my range slider output? For example, transforming 1.9 to 1.90 or 2 to 2.00. Additionally, is it feasible to have an input field where the user enters a pri ...