How to Defer the reCAPTCHA Script

Considering deferring the loading of the reCAPTCHA script until after the page has completely loaded? This approach can be beneficial for optimizing page load times and improving overall user experience. By deferring the script, you ensure that other critical resources, such as content and images, are prioritized during the initial page load, preventing potential slowdowns or interruptions.

Additionally, deferring the reCAPTCHA script can help mitigate issues related to script blocking or conflicts with other scripts on the page. Since reCAPTCHA is often used for form validation or submission, delaying its loading until after the page has loaded allows for smoother execution and interaction with the form elements.

In this tutorial, we’ll explore how to implement this optimization technique, providing step-by-step guidance on deferring the reCAPTCHA script loading using a simple snippet of code.

Deferrinf the script

To begin, you’ll need to copy this snippet to your site. For help on how and where to add snippets to your site, please check out this tutorial.

/**
 * Defer the reCAPTCHA script until after the page loads
 *
 * @link https://wpforms.com/developers/how-to-defer-the-recaptcha-script/
 */

function wpf_recaptcha_add_async_defer( $tag, $handle ) {

            if ( strpos( $tag, 'recaptcha/api.js?onload=wpformsRecaptchaLoad' ) !== false ) {
                $tag = str_replace( ' src', ' defer async="async" src', $tag );
            }

            return $tag;

        }

add_filter( 'script_loader_tag', 'wpf_recaptcha_add_async_defer', 99, 2 );

And that’s all you need to defer the reCAPTCHA JavaScript. Would you like to also change the theme for reCAPTCHA? Check out our tutorial on How to Change the Captcha Theme on Google Checkbox v2 reCAPTCHA.

Reference Filter

script_loader_tag

FAQ

Q: What if I want to defer hCAPTCHA?

A: To defer the hCAPTCHA script, please use this snippet instead.

/**
 * Defer the reCAPTCHA script until after the page loads
 *
 * @link https://wpforms.com/developers/how-to-defer-the-recaptcha-script/
 */

function wpf_hcaptcha_add_async_defer( $tag, $handle ) {

    if ( strpos( $tag, 'hcaptcha.com/1/api.js?onload=wpformsRecaptchaLoad' ) !== false ) {

        $tag = str_replace( ' src', ' defer async="async" src', $tag ); 
    }

    return $tag;

}
    add_filter( 'script_loader_tag', 'wpf_hcaptcha_add_async_defer', 99, 2 );