我正在尝试在我的组件中动态加载js脚本。
我有一个使用reCAPTCHA的联系人组件,问题是每次用户访问组件时,外部脚本都会加载。
export class ContactCmp {
captchaReady = false;
constructor() {
}
ngOnInit() {
if(){ //check if script is already loaded
this.loadScript('https://www.google.com/recaptcha/api.js', this.captchaLoaded);
}
else{
console.log("captcha is already loaded.")
}
}
captchaLoaded(){
console.log("Captcha loaded");
this.captchaReady = true;
}
loadScript(url, callback)
{
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.onreadystatechange = callback;
script.onload = callback;
head.appendChild(script);
}
}
如何检查脚本是否已加载?
答案 0 :(得分:2)
使用
document.querySelector('script[src="https://www.google.com/recaptcha/api.js"]');
测试脚本标记是否已存在
或检查是否存在window.__google_recaptcha_client