Add async script

The script_loader_tag filter, added in version 4.1, addresses this issue. To add an async attribute to an enqueued script you can do:

/**
 * Add an aysnc attribute to an enqueued script
 * 
 * @param string $tag Tag for the enqueued script.
 * @param string $handle The script's registered handle.
 * @return string Script tag for the enqueued script
 */
function namespace_async_scripts( $tag, $handle ) {
    // Just return the tag normally if this isn't one we want to async
    if ( 'your-script-handle' !== $handle ) {
        return $tag;
    }
    return str_replace( ' src', ' async src', $tag );
}
add_filter( 'script_loader_tag', 'namespace_async_scripts', 10, 2 );

If you want to add an id to the script, you could add that in the str_replace() as well.

More information available via the article »Add Defer & Async Attributes to WordPress Scripts« by Matthew Horne and the developer reference to script_loader_tag.

Leave a Comment