Advanced Speed Improvements: Load Deferred reCAPTCHA for Contact Form 7


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

Advanced Speed Improvements: Load Deferred reCAPTCHA for Contact Form 7   Advanced Speed Improvements: Load Deferred reCAPTCHA for Contact Form 7

Google PageSpeed Insights Diagnostics Before and After Speed Technique was Applied

Advanced Speed Improvements: Load Deferred reCAPTCHA for Contact Form 7

Advanced Speed Improvements: Load Deferred reCAPTCHA for Contact Form 7

GTmetrix Page Details Before and After Speed Technique was Applied

Advanced Speed Improvements: Load Deferred reCAPTCHA for Contact Form 7

Advanced Speed Improvements: Load Deferred reCAPTCHA for Contact Form 7

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.

Advanced Speed Improvements: Load Deferred reCAPTCHA for Contact Form 7

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