Loading reCAPTCHA asynchronously

59 Views Asked by At

I am using Google reCAPTCHA on my Laravel site. Everything works fine, but loading the reCAPTCHA slows down the loading of the site page by almost 2 times. I read your documentation (Loading reCAPTCHA https://developers.google.com/recaptcha/docs/loading) and did the following:

  1. I added async to the loading script:
 <div id="container" class="container">
      <script async src="https://www.google.com/recaptcha/api.js?hl=&render=MY_KEY"></script>
  1. Added a script:
<script>
            if (typeof grecaptcha === 'undefined') {
                grecaptcha = {};
            }
            grecaptcha.ready = function(cb) {
                if (typeof grecaptcha === 'undefined') {
                    const c = '___grecaptcha_cfg';
                    window[c] = window[c] || {};
                    (window[c]['fns'] = window[c]['fns'] || []).push(cb);
                } else {
                    cb();
                }
            }
            grecaptcha.ready(function() {
                grecaptcha.render("container", {
                    sitekey: 'MY_KEY'
                });
            });
</script>

After that, I got an error:

TypeError: grecaptcha.render is not a function. (In 'grecaptcha.render("container", {
sitekey: 'MY_KEY'
})', 'grecaptcha.render' is undefined)

Could you please tell me what mistake I made and what I can do to fix it?

0

There are 0 best solutions below