Would you like to speed up your page load times by optimizing when reCAPTCHA loads? By deferring the reCAPTCHA script until after your page content loads, you can improve initial page speed and user experience. This approach ensures your essential content appears quickly while security features load seamlessly in the background.
This guide will show you how to delay reCAPTCHA loading for better performance.
Understanding the Script Deferral
When reCAPTCHA loads normally, it can temporarily pause other resources from loading. By deferring the script, you allow your page’s critical content like text and images to load first. This creates a smoother experience for your users while maintaining the security benefits of reCAPTCHA.
Adding the Defer Code
To defer reCAPTCHA loading, add this code snippet to your site. If you need help adding custom code, please review our tutorial on adding code snippets.
This code works by identifying the reCAPTCHA script and adding both defer
and async
attributes. These attributes tell the browser to:
- Load the script asynchronously, without blocking other resources
- Execute the script only after the page has finished loading
Using with hCAPTCHA
If you’re using hCAPTCHA instead of reCAPTCHA, use this alternative version:
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 );
And that’s all you need to defer the reCAPTCHA JavaScript. Next, would you like to also change the theme for reCAPTCHA? Check out our tutorial on changing the CAPTCHA theme for more details.