Phil Kurth
/ Tips /

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

Last updated • 16 October 2019

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 );

Got a project in mind?
Let's talk.

Every project starts with a conversation about what you need. You hear back the same or next business day. If I'm not the right fit, I'll say so. If I am, you get a fixed quote before any work starts.

Phil Kurth, web designer and developer in Geelong