Add async script

I am working on a plugin that has to inject a script on pages (something like RefTagger), which would be easy using wp_enqueue_script, but there are two reasons I cannot do that: the script tag has to have an ID and it should be executed asynchronously.

I found three possible solutions but I don’t really like any of them:

  1. Just echo the script in wp_footer
    This is the easiest one and I have complete control over the script tag, but it is probably frowned upon (I intend to submit my plugin to the Plugin Repository so any advice regarding official guidelines is welcome).
  2. Use the standard functions and use filters to modify the script tag. The answers for this question detail the process, my problem is that it is very hacky (and probably could break in the future) and adding logic to clean_url has a performance cost – for one single script tag.
  3. Create a snippet that dynamically injects the script, save it as a file and use the standard methods. This is a very clean way but there is one more script to download, meaning slower page loads.

Is there any other way to do this, or is any of my solutions acceptable?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x