Skip to main content
Snippets

Make JavaScript Asynchronous

By March 29, 2016No Comments

Simple script optimization to make all external JavaScript asynchronous which will improve page load time. I wrote this into a plugin on our WordPress MultiSite network. This is not necessary in footer scripts so below we add the async attribute to all scripts then remove from the footer.

// Add async to all scripts

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

// Remove async function from footer scripts

function remove_js_async_head(){
    
	remove_filter( 'script_loader_tag', 'js_async_attr');
}
add_action( 'wp_head', 'remove_js_async_head', 100);

What exactly does it do?

It takes this < script type="text/javascript" src="url-to-reseource.js"> and appends async="async" just after type declaration. So the final result looks like this:

< script type="text/javascript" async="async" src="url-to-reseource.js"><script src="url-to-reseource.js" type="text/javascript"></script>

 

https://developers.google.com/speed/docs/insights/BlockingJS#deferJS

Tutorial to Add Defer and Async Attributes to Render Blocking Javascript in WordPress

Contact us to learn more about Adopt the Web for your business

Author Jarod Thornton

More posts by Jarod Thornton