Add Async, defer, or Any Other Attribute to WordPress scripts.
Posted in:I recently ran into an issue in trying to add FontAwesome to a WordPress theme. FontAwesome introduced Kits back in May of last year. To use a kit you simply include a and viola, magic icons! In WordPress this is done with the wp_enqueue_script()
function. However, I needed to include icons in pseudo elements which required that the attribute data-search-pseudo-elements
be added to the script tag.
Without much time to research I opted to simply hard code the script tag into the header of my theme without using WordPress’s built in functionality. This was incorrect.
script_loader_tag
The script_loader_tag filter
in WordPress allows us to add any attribute to an enqueued script. This can be used for defer
, async
, or any other attribute needed in the script tag.
/*
* Add async attributes to enqueued scripts where needed.
* The ability to filter script tags was added in WordPress 4.1 for this purpose.
*/
add_filter( 'script_loader_tag', function ( $tag, $handle, $src ) {
// the handles of the enqueued scripts we want to async
$scripts = array( 'fontawesome', 'another-script' );
if ( in_array( $handle, $scripts ) ) {
return '<script type="text/javascript" src="' . $src . '" data-search-pseudo-elements></script>';
}
return $tag;
}, 10, 3 );
The script_loader_tag
filter was introduced early in WordPress 4.1. This filter is run whenever wp_enqueue_script()
function is used.