Skip to content

Instantly share code, notes, and snippets.

@moxdev
Last active June 15, 2016 20:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moxdev/1ef8d3650cbccb3b738460bc2aa7f4cb to your computer and use it in GitHub Desktop.
Save moxdev/1ef8d3650cbccb3b738460bc2aa7f4cb to your computer and use it in GitHub Desktop.
If you need to load an enqueued script asynchronously in WordPress, or modify the <script> element in any other way, you can use code like the following:
/**
* Add async attributes to enqueued scripts where needed.
* The ability to filter script tags was added in WordPress 4.1 for this purpose.
* http://scottnelle.com/756/async-defer-enqueued-wordpress-scripts/
*/
function my_async_scripts( $tag, $handle, $src ) {
// the handles of the enqueued scripts we want to async
$async_scripts = array( 'some-script', 'another-script' );
if ( in_array( $handle, $async_scripts ) ) {
return '<script type="text/javascript" src="' . $src . '" async="async"></script>' . "\n";
}
return $tag;
}
add_filter( 'script_loader_tag', 'my_async_scripts', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment