Load chosen scripts with defer or async using WordPress's built-in loading strategy, which respects script dependencies.
add_action( 'wp_enqueue_scripts', function (): void {
// Script handles to defer: they run after the HTML is parsed, in order.
$defer = [ 'contact-form-7', 'comment-reply' ];
// Script handles to load async: they run as soon as they download, in any order.
$async = [];
foreach ( $defer as $handle ) {
if ( wp_script_is( $handle, 'registered' ) ) {
wp_script_add_data( $handle, 'strategy', 'defer' );
}
}
foreach ( $async as $handle ) {
if ( wp_script_is( $handle, 'registered' ) ) {
wp_script_add_data( $handle, 'strategy', 'async' );
}
}
}, 100 );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
Scripts loaded in the page head without defer or async block the page from rendering until they’ve downloaded and run. Since WordPress 6.3 there’s a built-in way to change that for any registered script, so you no longer need to rewrite <script> tags with string replacement.
The snippet runs late on wp_enqueue_scripts, after themes and plugins have registered their scripts, and sets a loading strategy on each handle you list. WordPress then adds defer or async to the tag itself.
The big advantage over the old string-replacement approach is that WordPress checks dependencies. If another script depends on the one you defer and still loads normally, WordPress won’t defer it, because that would break the dependent script. The old method added the attribute blindly and could break things that way.
View the page source: each script tag has an id like contact-form-7-js. The handle is that id without -js. The Query Monitor plugin also lists every enqueued script with its handle.
View the source and find the script’s tag. It should now include defer or async and a data-wp-strategy attribute. Then check the feature that script powers still works.