我正在尝试将 Google Pay 作为组件集成到应用程序中。我需要在执行任何操作之前加载 Google Pay Javascript 文件。这就是我正在做的事情:
onMounted(()=>{
const scripts = [
"https://pay.google.com/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);
我将超时设置为500
任意值,因为我不知道https://pay.google.com/gp/p/js/pay.js
脚本加载需要多长时间。
除了使用函数之外,有没有更好的方法来等待脚本加载并准备就绪setTimeout()
?
setTimeout()
是的,您可以监听脚本的事件,以确保在执行您的函数load
之前脚本已经完全加载,而不是使用。loadGooglePay()
解释:
onload
事件:这确保loadGooglePay()
仅在脚本完全加载后运行。loadGooglePay()
立即调用。这种方式比之前更加可靠
setTimeout()
,可以保证脚本只加载一次,提高效率