Performance PHP Intermediate

Defer or Async Scripts the WordPress Way

Load chosen scripts with defer or async using WordPress's built-in loading strategy, which respects script dependencies.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 18 lines
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 );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

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.

How it works

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.

Defer or async?

  • Defer is the safe choice for most scripts. They run after the page is parsed, in the order they appear.
  • Async suits independent scripts such as analytics tags, which can run whenever they arrive.

Finding script handles

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.

How to test it

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.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only