Add async, defer and other attributes to script tags in WordPress
The wp_enqueue_script() function does not let you set script attributes such as async or defer. Here is how to solve that, and how to use wp_enqueue_script() to load jQuery or Bootstrap from a CDN with the integrity and crossorigin attributes.
Intro
At the start of their careers, most WordPress developers add styles and scripts with plain tags. Later they learn the best practice: the wp_enqueue_style and wp_enqueue_script functions. The next step is realising that these functions do not let you run a script asynchronously with async or defer. You can also run into trouble when loading Bootstrap or jQuery from a CDN, because that needs the integrity and crossorigin attributes.
async vs defer
Scripts are usually placed in the footer. This is good for the user: the browser loads the HTML first, the visitor can start reading, and only then are scripts downloaded and executed. Sometimes, though, a script has to go in the header or in the middle of the body. When the browser reaches such a script, it stops, downloads and executes it, and only then renders the rest of the page. This synchronous behaviour is not always convenient. To make page rendering independent of script loading, use the async or defer attribute:
deferdownloads the script in parallel and runs it after the HTML has been parsed. Deferred scripts run in the order they appear in the document.asyncdownloads the script in parallel and runs it as soon as it is ready, without waiting for the HTML or for other scripts. The order is not guaranteed, so use it only for independent scripts such as analytics.
Add the attributes with the script_loader_tag filter
Should we give up the WordPress team’s recommendation and add scripts by hand? No: hardcoding tags is bad practice and breaks dependencies, so keep using wp_enqueue_script() and change the generated tag with the script_loader_tag filter:
add_filter( 'script_loader_tag', 'helloadmin_script_attributes', 10, 3 );
function helloadmin_script_attributes( $tag, $handle, $src ) {
// Script handles that get async.
$async = array( 'font-awesome' );
// Script handles that get defer.
$defer = array( 'some-script', 'any-script' );
// Scripts loaded from a CDN: handle => integrity hash.
$cdn = array(
'jquery-cdn' => 'sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=',
'bootstrap' => 'sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa',
);
if ( in_array( $handle, $async, true ) ) {
$tag = str_replace( ' src=', ' async src=', $tag );
} elseif ( in_array( $handle, $defer, true ) ) {
$tag = str_replace( ' src=', ' defer src=', $tag );
}
if ( isset( $cdn[ $handle ] ) ) {
$tag = str_replace( ' src=', ' integrity="' . esc_attr( $cdn[ $handle ] ) . '" crossorigin="anonymous" src=', $tag );
}
return $tag;
}
The filter edits the tag that WordPress has already built instead of returning a new one. This matters: $tag can also contain inline code added with wp_localize_script() or wp_add_inline_script(), and a hand-built <script> would silently drop it.
The handles must match the ones you pass to wp_enqueue_script(). For example, to load jQuery from a CDN, register it under its own handle (the integrity hash above belongs to this exact jQuery file):
add_action( 'wp_enqueue_scripts', 'helloadmin_enqueue_scripts' );
function helloadmin_enqueue_scripts() {
wp_deregister_script( 'jquery' );
wp_register_script( 'jquery-cdn', 'https://code.jquery.com/jquery-3.2.1.min.js', array(), null, true );
wp_register_script( 'jquery', false, array( 'jquery-cdn' ), null, true );
wp_enqueue_script( 'jquery' );
}
The empty jquery handle depends on jquery-cdn, so every script that lists jquery as a dependency still works.
Things to keep in mind
- Do not add
deferorasyncto jQuery itself. Inline scripts from plugins often calljQueryright away and break if jQuery has not run yet. - The integrity hash must match the exact file version. If you change the version in the URL, take the new hash from the CDN.
- In HTML5 the
type="text/javascript"attribute is not needed.
Update for WordPress 6.3+: core now supports loading strategies directly. Pass array( 'strategy' => 'defer', 'in_footer' => true ) as the last argument of wp_enqueue_script() instead of filtering the tag. WordPress then also checks the dependencies and will not defer a script that a blocking script depends on.
Sources: