# Core Web Vitals WordPress Improve Recaptcha Performance

- Link: https://www.agilicus.com/core-web-vitals-wordpress-improve-recaptcha-performance/
- Published: 2021-03-18T15:26:14+00:00
- Author: Don Bowman

Your website is based on WordPress. You use “[Easy Forms for Mailchimp by Yikes](https://wordpress.org/plugins/yikes-inc-easy-mailchimp-extender/)“.
You use Google Recaptcha to prevent Spam as well as [Akismet](https://wordpress.org/plugins/akismet/).
However, your [Core Web Vitals](https://web.dev/) 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](https://www.agilicus.com/speedup-wordpress-dequeue-scripts/) for [Performance](https://www.agilicus.com/the-quest-for-web-site-performance-perfection/).

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](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script)):

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

    ```php
    // 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.
