Automatically Add Defer or ASYNC to all JS files (no matter where they are located)

Here”s a solution to your question. This doesn’t take into account the merit of whether or not you should add async or defer to certain assets, it just gives you the tools to do it yourself, or not.

Points to note:

  • this is only for use with Javascript includes (obviously)
  • It’s not 100% accurate because of the method of replacing the tag text, but for 99.9% of the javascript includes you’ll have, it’ll do the job the fine.
  • there is the option to specify which includes should have the async and defer tags, simply add the handles of the assets you want to apply it to. I’ve included JQuery for starters.
  • this code add both defer="defer" and async. Simply delete either of the appropriate if blocks if that’s not what you want.
function add_async_to_js( $includeTag, $handle ) {

    $handlesToChange = [
        'jquery'
    ];

    if ( in_array( $handle, $handlesToChange ) ) {
        if ( strpos( $includeTag, ' defer=" ) === false ) {
            $includeTag = str_replace( " src="https://wordpress.stackexchange.com/questions/390443/," defer="defer" src=", $includeTag );
        }
        if ( strpos( $includeTag, " async' ) === false ) {
            $includeTag = str_replace( ' src="https://wordpress.stackexchange.com/questions/390443/," async src=", $includeTag );
        }
    }
    return $includeTag;
}

add_filter( "script_loader_tag"https://wordpress.stackexchange.com/questions/390443/,"add_async_to_js', 10, 2 );