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
);
Leave a Reply