How to Defer the reCAPTCHA Script

Overview

Would you like to defer the recAPTCHA script from loading until after the page has loaded? This small snippet will show you how to do this.

Adding 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.

Filter Reference: 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 );