Async JavaScript WordPress Filter

Browser support for the async attribute is available in most modern browsers, caniuse.com provides detailed browser support information. You should check your visitor stats and consider if this treatment is right for your website.

<?php 
/**
Asynchronous JavaScript relies on adding an async attribute to the script tag. With that attribute, the browser deals with loading the file asynchronously.
*/
function pwcc_async_scripts( $tag, $handle ) {
  switch ( $handle ) {
    case 'picturefill'  : // falls through
    case 'pwcc-scripts' : 
      $tag = str_replace( '></script>', ' async></script>', $tag );
  }

  return $tag;
}

add_filter( 'script_loader_tag', 'pwcc_async_scripts', 10, 2 );


/**
Asynchronous JavaScript files can be loaded in the HTML header (they don't block rendering), so we can move the files above to the header and get them downloading if we wish.

Specifying the script load in Group 0, is to specify the load in the HTML header. In a real world example, one would name these libraries once in an array available to both functions.

WARNING: the async attribute is not supported in most Opera mobile editions or IE10 and earlier, so will block rendering in these browsers. Check your visitor stats before making this change.
 */
function pwcc_async_to_header() {
  global $wp_scripts;
  $wp_scripts->add_data( 'picturefill',  'group', 0 );
  $wp_scripts->add_data( 'pwcc-scripts', 'group', 0 );
}
add_action( 'wp_enqueue_scripts', 'pwcc_async_to_header', 99 );

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.