Advanced Speed Improvements: Load Deferred reCAPTCHA for Contact Form 7

A white, rounded square logo with an abstract S-shaped design on a gradient blue and purple background.

In this post, we will demonstrate an advanced site speed improvement technique by deferring the loading of reCAPTCHA files when using Contact Form 7 for WordPress websites.

[Please note, this technique will not work for Contact Form 7 version 5.2 and beyond. The latest updates to the plugin caused our code to no longer work. However, we are looking into a new method and will update this post when the time comes.]

We have discovered that using certain functionality, like Google’s reCAPTCHA script to fight form spam can actually harm your site speed. The issue is this functionality is dependent on loading numerous third party JavaScript and CSS files preemptively when a form may not even be used by the visitor. This functionality adds extra weight and requests in order for the website to load which is not recommended.

Therefore, our solution was to defer the loading of the reCAPTCHA script until a visitor interacts with the contact form.  Surprisingly, we were unable to find any methods online to accomplish this, so we developed our own technique that we will teach you later in this post.

We also want to demonstrate the performance upgrade you can expect to see after applying our advanced speed improvement technique. If you don’t already know, improving your site speed is beneficial to both your visitors and search engines. Fast loading sites provide visitors with a better user experience and search engines favor faster sites because they can crawl them more efficiently.

Google PageSpeed Insights Score Before and After Speed Technique was Applied

A circular gauge displaying the number 49 in red, indicating a website performance score. Below is the blurred URL "https://disabilityapplicationhelpers.com/" and a color-coded scale for score ranges.   A speed test score shows a rating of 65 out of 100, with a breakdown legend indicating ranges: 0-49 (red), 50-89 (yellow), and 90-100 (green).

Google PageSpeed Insights Diagnostics Before and After Speed Technique was Applied

A diagnostics report showing four bullet points with warnings about text visibility during webfont load, third-party code blocking, main-thread work, and JavaScript execution time.

Screenshot of a diagnostics report highlighting four issues: text visibility during webfont load, static asset caching, main-thread workload, and critical request chains, each with respective metrics.

GTmetrix Page Details Before and After Speed Technique was Applied

A screenshot showing page details: fully loaded time of 2.3 seconds, total page size of 1.37 megabytes, and 68 requests. All metrics show upward green arrows.

Screenshot of webpage performance metrics showing a fully loaded time of 1.9 seconds, total page size of 1.07 MB, and 56 requests.

Applying this speed improvement technique instantly boosted our overall score (in Google’s PageSpeed Insights) a whopping 16 points which is a huge improvement!

Also, when looking closer at the diagnostics, there was another performance gain. Google is no longer flagging the site to “Reduce the impact of third-party code” or “Reduce JavaScript execution time” which is directly correlated to the reCAPTCHA script being deferred. The update reduced the “main-thread work” execution time by over 3 seconds as well.

Lastly, when looking at the actual metrics regarding fully loaded time, total page size and requests, we can see improvements in each category after the update. The site has a slightly faster load speed, a reduction of 300kb in total page size and 12 less requests made.

How to Perform this Speed Improvement Technique

The first goal is to dequeue the Contact Form 7 script from the site. Within your theme’s functions.php file, simply add the following code.

add_action('wp_print_scripts', function () {
    wp_dequeue_script('google-recaptcha');
});

Just to ensure that the reCAPTCHA script is no longer loading, check the page source of a page on the site. In the footer, it should no longer show this script “https://www.google.com/recaptcha/api.js?render=YOUR_API_KEY&ver=3.0”. Once it is confirmed that the site is successfully dequeueing Contact Form 7’s scripts, we can move onto implementing the load deferring.

Create a new JavaScript file in your theme folder. You can name the file anything you’d like, but I will call it “recaptcha.js”. In this file, insert the code below.

var captchaLoaded = false;

$( document ).ready(function() {

//Load reCAPTCHA script when CF7 form field is focused
$(‘.wpcf7-form input’).on(‘focus’, function() {
// If we have loaded script once already, exit.
if (captchaLoaded)
{
return;
}

// Variable Intialization
console.log(‘reCAPTCHA script loading.’);
var head = document.getElementsByTagName(‘head’)[0];
var recaptchaScript = document.createElement(‘script’);
var cf7script = document.createElement(‘script’);

// Add the recaptcha site key here.
var recaptchaKey = ”;

// Dynamically add Recaptcha Script
recaptchaScript.type = ‘text/javascript’;
recaptchaScript.src = ‘https://www.google.com/recaptcha/api.js?render=’ + recaptchaKey + ‘&ver=3.0’;

// Dynamically add CF7 script
cf7script.type = ‘text/javascript’;

cf7script.text = “!function(t,e){var n={execute:function(e){t.execute(\”” + recaptchaKey +”\”,{action:e}).then(function(e){for(var t=document.getElementsByTagName(\”form\”),n=0;n<t.length;n++)for(var c=t[n].getElementsByTagName(\”input\”),a=0;a<c.length;a++){var o=c[a];if(\”g-recaptcha-response\”===o.getAttribute(\”name\”)){o.setAttribute(\”value\”,e);break}}})},executeOnHomepage:function(){n.execute(e.homepage)},executeOnContactform:function()
{n.execute(e.contactform)}};
t.ready(n.executeOnHomepage),document.addEventListener(\”change\”,n.executeOn
Contactform,!1),document.addEventListener(\”wpcf7submit\”,n.executeOnHomepage,!1)}(grecaptcha,{homepage:\”homepage\”,contactform:\”contactform\”});”;

// Add Recaptcha Script
head.appendChild(recaptchaScript);

// Add CF7 Script AFTER Recaptcha. Timeout ensures the loading sequence.
setTimeout(function() {
head.appendChild(cf7script);
}, 200);

//Set flag to only load once
captchaLoaded = true;
});
});

Now that you have added the JavaScript to the site, the final step (besides testing) is to enqueue our JavaScript file to the site. To do this, go back to your functions.php file and add the following code:

function cf7_defer_recaptcha() {
wp_enqueue_script(‘cf7recap’, get_template_directory_uri() . ‘/recaptcha.js’, array(‘jquery’), ‘1.0’);
}
add_action(‘get_footer’, ‘cf7_defer_recaptcha’);

Now that you have added the JavaScript to the site, the final step (besides testing) is to enqueue our JavaScript file to the site. To do this, go back to your functions.php file and add the following code:

function cf7_defer_recaptcha() {
    wp_enqueue_script('cf7recap', get_template_directory_uri() . '/recaptcha.js', array('jquery'), '1.0');
}
add_action('get_footer', 'cf7_defer_recaptcha');

That should be it for the code. Let’s take a look at the site and test it out! Theoretically, what we should see is the reCAPTCHA script load ONLY when we click into the input field of the form.

Open up your page with the contact form and your inspector tools, and navigate to the network tab.  Let the page load for a few seconds and then click into the Contact Form 7 input field, and you should see the reCAPTCHA script load in, similar to the screenshot below.

A browser network tab showing loading times for various scripts and resources, including "jquery.js," "autoptimize," and "gtm.js," with red arrows pointing to some of the items listing their respective load times.

Congratulations! You have officially implemented a load defer on Contact Form 7 scripts.

Questions or Feedback?

We would love to hear your feedback if this blog post has helped you to better understand how to make your site faster by deferring the loading of reCAPTCHA for Contact Form 7. Also, if you run into any issues, feel free to leave a comment below and we’ll do our best to help you out with a solution.

Share This

Join the Sales and Marketing News, receive our last insights, tips and best practices.

Our 7 Guarantees

Keeping 2,000+ Clients Happy Since 2001.

1
You Will Love Your Design We design to please you and your clients
2
Same-Day Support 24-hour turnaround edits during business hours
3
Free Education We provide knowledge to help you expand
4
No Hidden Charges We quote flat-rate projects
5
Own Your Site No strings attached
6
We Create Results SEO, PPC, content + design = clients
7
We Make Life Easier One agency for web, branding and marketing