WP-Mix

A fresh mix of code snippets and tutorials

Add Defer and Async to WordPress Enqueued Scripts

When adding JavaScript in WordPress, it sometimes is necessary to add attributes such as async and defer to the <script> tag. Here is a technique to do it with any WordPress version 4.1 and better.

Here is the magic function:

// add async and defer attributes to enqueued scripts
function shapeSpace_script_loader_tag($tag, $handle, $src) {
	
	if ($handle === 'my-plugin-javascript-handle') {
		
		if (false === stripos($tag, 'async')) {
			
			$tag = str_replace(' src', ' async="async" src', $tag);
			
		}
		
		if (false === stripos($tag, 'defer')) {
			
			$tag = str_replace('<script ', '<script defer ', $tag);
			
		}
		
	}
	
	return $tag;
	
}
add_filter('script_loader_tag', 'shapeSpace_script_loader_tag', 10, 3);

This function first checks the JavaScript handle. If it is for our plugin, then two things happen. First the tag is checked for the async attribute; if not found then it is added. Likewise the second condition checks if the defer attribute is present; if not, then it is added. All of this happens by hooking the function into the script_loader_tag filter hook.

Customize as needed to add whichever attributes are necessary. Remember to change the my-plugin-javascript-handle to match the actual handle of your plugin’s or theme’s JavaScript file.

About async & defer

Also for reference, here is what the async and defer attributes are doing:

  • async — Asynchronous tells the browser to execute the script when ready, without blocking any HTML parsing
  • defer — Deferred tells the browser to delay script execution until HTML parsing is complete

Remember to test thoroughly by viewing the actual HTML output of your pages (via View Source or Inspector et al).

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress