Enqueue Scripts with ‘defer’ or ‘async’ attribute

First, add a filter for the script loader tag:

add_filter( 'script_loader_tag', array( $this, 'add_defer_attr' ), 10, 2 );

Then, enqueue the script, noting its WordPress handle (in this case ‘hotMessScripts’):

wp_enqueue_script(
 'hotMessScripts', 
 plugin_dir_url( __FILE__ ) . 'js/hotMessAdmin.js', 
 array('jquery', 'jquery-ui-sortable', 'jquery-ui-dialog')
);

Then, identifying the script’s handle, alter the script’s tag by inserting the desired ‘defer’ or ‘async’ attribute before the ‘src’ attribute:

/* Add defer attribute to hotMessAdmin.js script tag */
public function add_defer_attr( $tag, $handle ){
	if( $handle == 'hotMessScripts' ){
		return str_replace( ' src', ' defer="defer" src', $tag );
	} else {
		return $tag;
	}
}

Remember, all script tags will run through this filter. The unaltered tag must still be returned even for the scripts tags that should not be changed, thus the else clause is important.

Posted: Wednesday, January 9th, 2019
Category: Wordpress