最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to wait for an external script to be ready in Vue 3? - Stack Overflow

programmeradmin1浏览0评论

I am trying to integrate Google Pay as a component in an application. I need to load the Google Pay Javascript file before I perform any actions. This is what I am doing:

onMounted(()=>{
  const scripts = [
    ".js",
  ];

  // Append the pay.js script to the <head> tag
  scripts.forEach(script => {
    let tag = document.createElement("script");
    tag.setAttribute("src", script);
    tag.setAttribute("async", true);
    
    document.head.appendChild(tag);
  });

  //Check if Google Pay exists
  function isGooglePayReady(){
    if('google' in window && Object.keys(window.google).length) {
      loadGooglePay()
    }
}

// Have to currently use a setTimeout to wait for script to load
setTimeout(()=> isGooglePayReady(), 500);

I set the timeout to 500 arbitrarily because I don't know how long it at takes for the .js script to load be available.

Is there a better way to wait for the script to load and be ready than using a setTimeout() function?

I am trying to integrate Google Pay as a component in an application. I need to load the Google Pay Javascript file before I perform any actions. This is what I am doing:

onMounted(()=>{
  const scripts = [
    "https://pay.google/gp/p/js/pay.js",
  ];

  // Append the pay.js script to the <head> tag
  scripts.forEach(script => {
    let tag = document.createElement("script");
    tag.setAttribute("src", script);
    tag.setAttribute("async", true);
    
    document.head.appendChild(tag);
  });

  //Check if Google Pay exists
  function isGooglePayReady(){
    if('google' in window && Object.keys(window.google).length) {
      loadGooglePay()
    }
}

// Have to currently use a setTimeout to wait for script to load
setTimeout(()=> isGooglePayReady(), 500);

I set the timeout to 500 arbitrarily because I don't know how long it at takes for the https://pay.google/gp/p/js/pay.js script to load be available.

Is there a better way to wait for the script to load and be ready than using a setTimeout() function?

Share Improve this question asked Mar 6 at 17:44 volume onevolume one 7,58314 gold badges89 silver badges173 bronze badges 1
  • I made a similar workaround trying to minimize the delay, using setInterval() with 100ms and destroying the timer once done – pierpy Commented Mar 8 at 3:45
Add a comment  | 

1 Answer 1

Reset to default 1

Using the scripts onload and onerror events is most likely an option here I suppose.

  
  // Set up the onload handler before appending to DOM
  tag.onload = () => {
  //Check if Google Pay exists
  if ('google' in window && window.google.payments && window.google.payments.api) {
      loadGooglePay();
    } else {
      console.error("Where response???");
    }
  };
发布评论

评论列表(0)

  1. 暂无评论