Sometimes it’s useful to add the async or defer attributes to your script calls in order to prevent that script from blocking the rest of your page from rendering. This is particularly useful with third party scripts which you do not host in the same place as the rest of your site.
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. */ 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 );
The script_loader_tag
filter was added in WordPress 4.1 for specifically this purpose. It is run whenever a script tag is generated by WordPress using the wp_enqueue_script()
function. In this example we compare the script $handle
against a list of known scripts that we want to load asynchronously.
The post Add async, defer, or other attributes to enqueued WordPress scripts appeared first on Scott Nelle.