Load Recaptcha on form interaction

Great for Page Speed - Great for Core Web Vitals

Having been struggling with clients new focus on CWV (Core Web Vitals) - part of Google's new algorithm / metric on determining how good a website is, I've come across the issue of Recaptcha being a large library, that always loads on every page and was difficult to load async/defer on pages with multiple forms, without loading the library every time. This would drop page speed scores significantly, especially on mobile devices

Most of our clients have one or two forms embedded in popups on every page, as we know that moving a user to a new page to fill in an enquiry form leads to a drop in engagement, so we like to have short, simple and fast to submit forms that popup for our onpage Call To Actions (CTA).

Whilst the Page Speed score is an indication of how "in theory" a page would score, the reality is that the field data shows that most visitors have cached versions of commonly used js libraries, like reCaptcha or YouTube embed library (at 486Kb, this has a significant impact on page speeds if not cached).

So, to keep everyone happy, I wanted to find a way to only load and trigger reCaptcha on a form, when it was needed. One trusty Google later, and I came across the sample code you see, kudus to the people on this page on Stack Overflow

var reCaptchaFocus = function() {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://www.google.com/recaptcha/api.js?render=6LdvEswUAAAAADNVG2ng4ZIfA4mfKUJiuLmLgnUy';
    head.appendChild(script);

    var recaptchaInterval = setInterval(function() {
        if( !window.grecaptcha || !window.grecaptcha.execute ) { return; }

        clearInterval( recaptchaInterval );

        grecaptcha.execute('6LdvEswUAAAAADNVG2ng4ZIfA4mfKUJiuLmLgnUy', {action: 'homepage'}).then(function(token) {
            document.getElementById('g-recaptcha-response').value=token;
        });
    }, 100 );
    document.getElementById('form').removeEventListener('focus', reCaptchaFocus);
};
document.getElementById('form').addEventListener('focus', reCaptchaFocus, false);
10