Loading Javascript asychronously in WordPress

There are a lot of simple things you can do to improve the performance of a web site. One of those things is, using asynchronous scripts.

Instead of <script src="script.js">, write <script src="script.js" async defer>. It unblocks page rendering of a browser, that regular javascript loading causes.

This works in almost any browser, even in old ones like IE 5.5. Newer browser support the async attribute. For older browsers, defer is a fallback if async is not supported.

WordPress does not have a built-in function to load Javascript asychronously. But version 4.1 introduced the script_loader_tag filter. This makes it possible to change how a script is loaded. You can use the script handle set by the wp_enqueue_script function to select scripts that should load in a non-blocking manner.


function my_async_scripts( $tag, $handle, $src ) {
  switch( $handle ) {
    case 'script-handle-1':
    case 'script-handle-2':
    case 'script-handle-3':
      $tag = str_replace( '<script', '<script async defer', $tag );
      break;
  }

  return $tag;
}
add_filter( 'script_loader_tag', 'my_async_scripts', 10, 3 );

Ensure that asynchronous scripts do not have any dependencies, because the order in which these scripts are loaded cannot be guaranteed.

Reference