7

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?

1

1 Answer 1

10

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.