reCAPTCHA

Contents

20 pts.

Implement lazy load without firing off a second script – combine 3 separate scripts into a single script:

<!-- Lazy load Google reCAPTCHA script after 3 seconds -->
<script>
setTimeout(function () {
    var script = document.createElement('script');
    script.src = "https://www.google.com/recaptcha/api.js?render=6LcvN34jAAAAABrc2JrhYaMKKY2WIv6ZKHMmy28L";
    script.async = true;
    script.defer = true;
    script.onload = function() {
        // Ensure reCAPTCHA is ready after loading
        grecaptcha.ready(function () {
            grecaptcha.execute('6LcvN34jAAAAABrc2JrhYaMKKY2WIv6ZKHMmy28L', { action: 'submit' }).then(function (token) {
                // Set the generated token to the #token_generate form input.
                var response = document.querySelectorAll("[id=token_generate]");
                for (var e = 0; e < response.length; e++) {
                    var responseItem = response[e];
                    responseItem.value = token;
                }
            });
        });
    };
    document.head.appendChild(script);
}, 3000); // Delay for 3 seconds
</script>
Updated on October 21, 2024
Was this article helpful?

Related Articles