1

I'm trying to load js script dynamically in my component.

I have a contact component which uses reCAPTCHA, the problem with it that everytime the user visits the component, the external script loads.

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);
}

}

How can I check if the script is already loaded?

Murhaf Sousli
  • 12,622
  • 20
  • 119
  • 185

1 Answers1

2

use

document.querySelector('script[src="https://www.google.com/recaptcha/api.js"]'); 

to test if the script tag already exists

or check for the existence of window.__google_recaptcha_client

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87