How to completely defer loading Google reCaptcha until after the page fully loads

Viewed 5644

I have Google reCaptcha v2 (checkbox type) installed on the website. But it's slowing down the page loading significantly on mobile even with the 'defer' attribute (based on pagespeed test). So, I want to defer its loading completely until after the page is fully loaded.

This is what the form code (where the reCaptcha is installed) looks like:

    <form id="sib-form" method="POST" action="https://.........." data-type="subscription">
       <input class="input" type="text" id="FIRSTNAME" name="FIRSTNAME" data-required="true">
       <input class="input" type="text" id="LASTNAME" name="LASTNAME" data-required="true">

       <script>function handleCaptchaResponse() { 
       var event = new Event('captchaChange'); document.getElementById('sib-captcha').dispatchEvent(event); 
       } </script>  

       <div class="g-recaptcha sib-visible-recaptcha" id="sib-captcha" data-sitekey="xxxxxxxxxxxxx" 
       data-callback="handleCaptchaResponse"></div>

       <button form="sib-form" type="submit">Subscribe</button>      
       <input type="text" name="email_address_check" value="" class="input--hidden">        
       <input type="hidden" name="locale" value="en">
    </form>

And this reCaptcha js file is added in the head section:

    <script defer src="https://www.google.com/recaptcha/api.js?hl=en"></script>

Even though the 'defer' attribute is used on this js file, other related files are loaded regardless. And they're the reason for the lower page speed.

How to defer the loading of this reCaptcha completely until after everything else is fully loaded?

1 Answers

IMHO, I think you should use IntersectionObserver to observer the element which contains the recaptcha. When the element isIntersecting you can add the api script at the end of body tag

var io = new IntersectionObserver(
    entries => {
        console.log(entries[0]);
        if (entries[0].isIntersecting) {
            var recaptchaScript = document.createElement('script');
            recaptchaScript.src = 'https://www.google.com/recaptcha/api.js?hl=en';
            recaptchaScript.defer = true;
            document.body.appendChild(recaptchaScript);
        }
    },
    {
        root: document.querySelector('.page-wrapper'),
        rootMargin: "0px",
        threshold: 1.0,
    }
);
io.observe(initForm);

Check more information about IntersectionObserver here: https://developers.google.com/web/updates/2016/04/intersectionobserver

Good luck

Related