Site icon Rez72 Application Development

Defer & Async Attributes when Enqueuing WP Scripts

Defer Async Delivery Options for WordPress

The following are notes on the provision of async/defer delivery options of scripts delivered via wp_enqueue_scripts. This was first introduced in WordPress (WP) ver 4.1, with the current WP codex documentation woefully thin.

Here is a full example of using the code as required:


add_filter('script_loader_tag', 'add_defer_attribute_lazy', 10, 2);
function add_defer_attribute_lazy($tag, $handle) {

if ( 'jquerylazyload' !== $handle ) {
return $tag; } else {
return str_replace( ' src', ' async="async" src', $tag ); }
}

 

This code should follow outside of the enqueued scripts routine. It is wrapped as a conditional, targeting the handle of each script individually as included in wp_enqueue_scripts. The string replace function will accept async or defer, adding such ahead of the src attribute. As noted a version of this code will need to be used for each script. If not using this method, the enqueued scripts are delivered in the standard manner. Currently, this only works for scripts, not styles.

Please consider these notes as a modest modification to the previous post entitled “Page Load Speed and Code Bloat”.

Exit mobile version