How to add defer or async attributes to WordPress Script

In this article we are going to show how to add async or defer attribute in script. WordPress developer often feels typical and attempt wrong way to add attributes in scripts because sometimes script is added by function. Developer feels typical to add attributes in easy attempt in that particular case of wordpress. Here in this article we are adding async or defer through hooks as we are implementing add_filter to get action on all script.

Async Defer Attribute - PHPCluster
Async Defer Attribute – PHPCluster

Here you can set attributes as you require in script.
Asynchronous: In this script executes when it becomes ready and do not interrupt HTML parsing.
Defer : In this case script is executed after html is parsed completely.

Add this code in function.php file

//function to add defer to all scripts

function  add_defer_tojs($tag)
{
return str_replace( ' src', ' defer="defer" src', $tag );
}
add_filter( 'script_loader_tag', 'add_defer_tojs', 10 );

//function to add async to all scripts

function add_async_tojs($tag)
{
return str_replace( ' src', ' async="async" src', $tag );
}
add_filter( 'script_loader_tag', ' add_async_tojs ', 10 );

If you are using any attributes you should test is there any script that is working or not and if get an issue just remove that particular attribute from scripts. That’s it.

Leave a Comment