Using async and defer with wp_enqueue_script()

Jul 27, 2019

The wp_enqueue_script() function doesn’t support async/defer by itself, but luckily the script_loader_tag hook allows us to manipulate the wp_enqueue_script() output really easily.

<?php

function wpa_add_enqueue_script_attributes( $tag, $handle ) {
	// Add defer
	if( 'my-handle' === $handle ) {
		 return str_replace( ' src="', ' defer src="', $tag );
	}

	// Add async
	if( 'another-handle' === $handle ) {
		 return str_replace( ' src="', ' async src="', $tag );
	}

	// Add multiple defers
	$deferrable_handles = [
		'first-handle',
		'second-handle',
		'third-handle',
	];

	if( in_array( $deferrable_handles ) ) {
		return str_replace( ' src="', ' defer src="', $tag );
	}

	return $tag;
}

add_filter('script_loader_tag', 'wpa_add_enqueue_script_attributes', 10, 2);

And that’s it. Easy enough?

Comments

avatar
  Subscribe  
Notify of