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.
Since Version 4.1 a new filter was introduced that finally provides a simple way to add async/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 the “defer” attribute 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 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 three 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. 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?
Updated: 25/08/2022
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 script handles.
Defer
function add_defer_attribute($tag, $handle) { // add script handles to the array below $scripts_to_defer = array('my-js-handle', 'another-handle'); foreach($scripts_to_defer as $defer_script) { if ($defer_script === $handle) { 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) { // add script handles to the array below $scripts_to_async = array('my-js-handle', 'another-handle'); foreach($scripts_to_async as $async_script) { if ($async_script === $handle) { 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.