Add Defer & Async Attributes to WordPress Scripts

WordPress developers often enqueue scripts incorrectly and sometimes it was done for a reason because WordPress didn’t have a simple way to add the new’ish async and defer attributes, but that is no longer the case.

Since Version 4.1 a new filter has been introduced that finally provides a less painful solution to add async or defer attributes without bastardizing the process.

apply_filters ( 'script_loader_tag', string $tag, string $handle, string $src )

Usage

function add_async_attribute($tag, $handle) {
    if ( 'my-js-handle' !== $handle )
        return $tag;
    return str_replace( ' src', ' async="async" src', $tag );
}
add_filter('script_loader_tag', 'add_async_attribute', 10, 2);

If you want to use defer just replace async="async" with defer="defer".

Add this to your functions.php or equivalent file such as custom.php for Thesis.

You will need to change the handle which (if you enqueued your script correctly) will be the first parameter of the enqueue method.

wp_register_script('my-js-handle', $src, $deps, $ver, $in_footer);

How you choose which tag to use depends entirely on the nature of the script itself and there are 3 possible choices.

  • Standard – This is without the async or defer attribute and is the standard behavior for your browser.
  • Deferred – This delays the execution of the script until the HTML parser has finished.
  • Asynchronous – This executes when the script is ready and doesn’t disrupt HTML parsing.

As always you should test any changes you make and if you find that you have errors associated with either attribute then just don’t use them for that particular script.

What if you want to add the async or defer tag to multiple scripts?

In order to add the async/defer tag to multiple scripts we need to create an array and then loop through that array and add the async/defer tag to each script. Add either of these snippets to your themes functions.php or custom.php for Thesis 2 and edit the array to include your own script handles.

Defer

function add_defer_attribute($tag, $handle) {
   $scripts_to_defer = array('my-js-handle', 'another-handle');
   foreach($scripts_to_defer as $defer_script) {
      if ($async_script !== $handle) return $tag;
      return str_replace(' src', ' defer="defer" src', $tag);
   }
   return $tag;
}
add_filter('script_loader_tag', 'add_defer_attribute', 10, 2);

Async

function add_async_attribute($tag, $handle) {
   $scripts_to_async = array('my-js-handle', 'another-handle');
   foreach($scripts_to_async as $async_script) {
      if ($async_script !== $handle) return $tag;
      return str_replace(' src', ' async="async" src', $tag);
   }
   return $tag;
}
add_filter('script_loader_tag', 'add_async_attribute', 10, 2);

Let me know if you have any questions below.

 

In Category: WordPress