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?

2
  • if it's cached, which i'm sure google will make sure it is, then it should load right away anyway... Commented Jan 9, 2016 at 3:47
  • @dandavis it's not loading the right way Commented Jan 9, 2016 at 3:48

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

thanks this is what I needed if(!window['__google_recaptcha_client'])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.