Igor Simic
5 years ago

How to load async JavaScript in Wordpress

Loading async JS file in Wordpress is a needed feature when it comes to speed optimisation and page loading speed. So how to set up async tag on JavaScript loaded by Wordpress?

Async feature is not included in JS by default, so what he have to do is set up a filter on a script loading and modify the "<script></script>" tag.
In your function.php file, after you used wp_enqueue_script to define scripts which will be loaded we have to set up filter 'script_loader_tag':

// include script
wp_enqueue_script('owl-carousel', get_template_directory_uri() .'/assets/js/owl.carousel.min.js', array('angular-timeago'),'1.0',false);

// after that set this filter
add_filter('script_loader_tag', 'add_async_attribute', 10, 2);
Script loader tag filter will call add_async_attribute function which will have two params: $tag and $handle. $handle is a script name, in our example will be  owl-carousel (defined in wp_enqueue_script call), and $tag will be script tag (<script src="...."></script>) and this tag we need to change. 
So let's create that function:
function add_async_attribute($tag, $handle) {
                // set script names which will have async attribute
                $async_array = ['owl-carousel'];
                // add async attribute to src tag
                if( in_array($handle, $async_array) ){
                    return str_replace( ' src', ' async="async" src', $tag );
                    return $tag;
add_async_attribute function will just check is the script name in async_array and it will add async param to it script tag.