How to set defer or async attributes on enqueued script tags in WordPress

If you get down to business with performance optimisation, you could find yourself looking at ways to defer your scripts or even load them asynchronously.

As far as I’m aware, WordPress’ built-in functions wp_register_script() and wp_enqueue_script() don’t currently take arguments for defining these attributes. But, with WordPress being WordPress, there is usually a way and in this case, we just need to hook into the script_loader_tag filter and modify the HTML directly.

Here is a snippet to get you moving;

<?php
add_action( 'wp_enqueue_scripts', function () {
wp_register_script( 'my-script', get_stylesheet_directory_uri() . '/assets/js/my-script.js' );
wp_enqueue_script( 'my-script' );
} );
add_filter( 'script_loader_tag', function ( $tag, $handle ) {
if ( 'my-script' !== $handle ) {
return $tag;
}
return str_replace( ' src', ' defer src', $tag ); // defer the script
//return str_replace( ' src', ' async src', $tag ); // OR async the script
//return str_replace( ' src', ' async defer src', $tag ); // OR do both!
}, 10, 2 );

Need a website? Let's talk.

From website design & SEO through to custom WordPress plugin development. I transform ideas into dynamic, engaging, and high-performing solutions.
Subscribe to get the latest insights & updates in the world of web and how it impacts your business and website.
© 2024 Phil Kurth  |  All rights reserved.