Coding Triumph

Helpful code snippets & tutorials

How to defer parsing JavaScript in WordPress

It’s a good practice to delay parsing JavaScript until the page content is loaded. This will improve the page speed and offers a better user experience.

There are two HTML attributes you can use to defer JavaScript: defer and async.

<!-- async attribute -->
<script src= “path/to/script” async> </script>

<!-- defer attribute -->
<script src= “path/to/script” defer> </script>

In WordPress, scripts are not added directly to the HTML markup, instead, we use built-in functions to do that for us. So it can be a little bit tricky to add the two attributes to the script tags. Thankfully, we can always rely on the functions.php file to fix that. Here is the script:

/**
* Add this to functions.php file
*/

# the attributes are passed by the "script_loader_tag" hook
function defer_scripts(
    $tag, # The <script> tag for the enqueued script
    $handle, # The script's registered handle
    $src # The script's source URL
)
{
    // The handles of the enqueued scripts we want to defer
    $defer_scripts = [
	'script-one',
        'script-two',
        'script-three',
    ];

    if (in_array($handle, $defer_scripts)) {
	return '<script src="' . $src . '" defer="defer"></script>' . "\n";
    }

    return $tag;
}
# Filter the HTML script tag of an enqueued script.
# '3' stands for 3 arguments to be passed to the "defer_scripts" callback
add_filter( 'script_loader_tag', 'defer_scripts', 10, 3); 
If you like this post, please share
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments