Add async attribute to a Script Loaded By wp_enqueue_script

This is how you can add the async attribute to any JavaScript that is loaded by wp_enqueue_script. For example, say you are are loading a script with the handle of “google-adsense”, like this:

wp_enqueue_script( 'google-adsense' );

Then, you can add the async attribute to that HTML script tag, using the following code. In this example, the handle google-adsense is on line 5. You can change google-adsense to the handle of your own script.

/**
 * Add async attribute to the regular Adsense script.
 */
function isa_add_async_to_script( $tag, $handle, $src ) {
    if ( 'google-adsense' == $handle ) {
        return '<script async src="' . $src . '"></script>';
    }
    return $tag;
}
add_filter( 'script_loader_tag', 'isa_add_async_to_script', 10, 3 );

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]