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

Need a website?
Let's talk.

From website design and SEO through to custom WordPress plugins and web applications. Nearly twenty years of building for the web, and every project still starts the same way: a conversation about what you actually need.

Phil Kurth, web designer and developer in Geelong