• Skip to primary navigation
  • Skip to main content
Sal Ferrarello
  • About Sal Ferrarello
  • Speaking
  • Connect
    Mastodon GitHub Twitter (inactive)
You are here: Home / Dev Tips / WordPress JavaScript async defer

WordPress JavaScript async defer

Last updated on February 11, 2019 by Sal Ferrarello

I was adding ReCaptcha v2 on a site (see ReCaptcha v2 documentation) and one piece of the process was loading the ReCaptcha JavaScript.

Specifically, it wanted the script tag loaded as follows:

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

At the time of this writing, WordPress does not include a mechanism for adding async nor defer when loading a JavaScript file in the prescribed manner (using wp_enqueue_script()). See WordPress core tickets 12009 and 22249.

To add async and defer requires adding an additional filter on the script_loader_tag.

wp_enqueue_script(
    'recaptcha-v2',
    'https://www.google.com/recaptcha/api.js',
    [],
    null,
    true
);

// Add async and defer to 'recaptcha-v2' script loading tag.
add_filter(
    'script_loader_tag',
    function( $tag, $handle ) {
        // Check for the handle we used when enqueuing the script.
        if ( 'recaptcha-v2' !== $handle ) {
            return $tag;
        }
        // Add async and defer at the end of the opening script tag.
        return str_replace( '></', ' async defer></', $tag );
    },
    20,
    2
);
Sal Ferrarello
Sal Ferrarello (@salcode)
Sal is a PHP developer with a focus on the WordPress platform. He is a conference speaker with a background including Piano Player, Radio DJ, Magician/Juggler, Beach Photographer, and High School Math Teacher. Sal can be found professionally at WebDevStudios, where he works as a senior backend engineer.

Share this post:

Share on TwitterShare on FacebookShare on LinkedInShare on EmailShare on Reddit
Warning! This is a draft, not a finalized post. See full draft disclosure.

Filed Under: Dev Tips, Draft, Programming, Solution Tagged With: HTML5, JavaScript, WordPress

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2023 · Bootstrap4 Genesis on Genesis Framework · WordPress · Log in