Out of the box, WordPress does not include a async or defer attributes on javascript files loaded using wp_enqueue_script()
.
That’s okay, but some scripts you need them.
Learn how to add async
and defer
attributes to WordPress enqueued script
tags via functions.php
Code Sample
Here’s the code — paste it into your WP theme’s functions.php file and modify it appropriately, so it works on the enqueued script of your choosing.
/** * Add async and defer attributes 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 fhdigital_script_loader_tag($tag, $handle, $src) { // Check for a specific script to modify. if ($handle === 'YOUR-REGISTERED-SCRIPT-NAME') { // Check that 'async' isn't already declared. if (stripos($tag, 'async') === FALSE) { // Insert the 'async="async"' attribute and value. $tag = str_replace(' src', ' async="async" src', $tag); } // Check that 'defer' isn't already declared. if (stripos($tag, 'defer') === FALSE) { // Insert the 'defer' attribute. $tag = str_replace('<script ', '<script defer ', $tag); } } // Return the script tag in its final version. return $tag; } // Add a filter to run the script tag modification function. add_filter('script_loader_tag', 'fhdigital_script_loader_tag', 10, 3);
It’s basic WordPress hooks and actions (reference: WP version 4.1+).
Explanation
The action fhdigital_script_loader_tag
is hooked into WP’s script_loader_tag
hook and the rest is magic.
First, the script checks for your script’s registered name value. That way it only modifies the script(s) you tell it to modify and everything else is left unchanged.
Next, it checks for existing of async and defer attributes within the <script>
tag. If async and/or defer already exist nothing changes. If they do not exist then they’re added.
Lastly, the final version of the tag is returned for usage.
Async and Defer
For reference, here’s a brief rundown of what async and defer are doing.
ASYNC
async (i.e. “asynchronous”) tells the browser to execute the script when ready — without blocking HTML parsing.
DEFER
defer tells the browser to delay (i.e. “defer”) the script’s execution until after HTML parsing is finished.
Test and Debug
As with any new code, remember to test and debug thoroughly.
0 Comments