Blog / DevOps / Core Web Vitals WordPress Improve Recaptcha Performance

Core Web Vitals WordPress Improve Recaptcha Performance

Page Speed

Your website is based on WordPress. You use “Easy Forms for Mailchimp by Yikes“. You use Google Recaptcha to prevent Spam as well as Akismet. However, your Core Web Vitals WordPress score is too low, your are about to be penalised on search. How can you resolve this state of afairs? With Async and Defer for the scripts involved. Read on to see how I improved my site on my Quest for Performance.

Your web page has a large number of <script> tags. Each of these goes and fetches a bit of Javascript, parses it, runs it. That takes CPU and battery and network and time. The best thing you can do for performance is avoid the script entirely. If you cannot, try making the script simpler, shorter, smaller. If you cannot, in this case because Google Recaptcha is served via their CDN, the next best thing is to make it asynchronously load, deferring its needs until your page is loaded and visible.

So what are Async & Defer? Why do they matter for core web vitals in your wordpress? In a nutshell (see the <script> spec):

  • async — Tells the browser to execute the script when ready, without blocking any HTML parsing
  • defer — Tells the browser to delay script execution until HTML parsing is complete

OK, how can we add this to our WordPress web site? Well, we add a function to our theme functions.php. Below is the one I used, it defers all ‘yikes’, ‘akisment’, an ‘form-submission’. This causes the Google Recaptcha, the Yikes JS to load after the web page is up and visible.

// add async and defer attributes to enqueued scripts
function add_defer_async($tag, $handle, $src) {
if (! (stripos($handle, 'yikes') === false &&
stripos($handle, 'akismet') === false &&
stripos($handle, 'form-submission-helpers') == false)) {
if (false === stripos($tag, 'async')) {
$tag = str_replace(' src', ' async src', $tag);
}
if (false === stripos($tag, 'defer')) {
$tag = str_replace('<script ', '<script defer ', $tag);
}
}
return $tag;
}
add_filter('script_loader_tag', 'add_defer_async', 10, 3);

The above changed improved my Core Web Vitals on my WordPress from 56 to 92. It improved my Longest Content Paint to 2.2s from 4.4s. Your mileage may vary.

Leave a Reply

Your email address will not be published.