Wordpress Topics

How to Defer or Async JS Files On WordPress?

25/08/2023
Defer/Async JS Sources On Wordpress

To get better page performance and improve page loading defer or async to scripts. Use the codes below to add defer or async attributes to script tags.

Add Async to Scripts

Use the code below in functions.php to add async in scripts.

function add_async_attribute( $tag, $handle ) {
 // add script's id to the array below
 $scripts_to_async = array( 'jquery-core' );
  foreach( $scripts_to_async as $async_script ) {
  if ($async_script === $handle) {
   return str_replace( ' src', ' async="async" src', $tag );
  }
 }
 return $tag;
}

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

Add Defer to Scripts

Use the code below in functions.php to add defer in scripts.

function add_defer_attribute( $tag, $handle ) {
 // add script's id to the array below
 $scripts_to_defer = array( 'hcb-prism','hcb-script','clipboard');
 foreach( $scripts_to_defer as $defer_script ) {
  if ($defer_script === $handle) {
   return str_replace( ' src', ' defer="defer" src', $tag );
  }
 }
 return $tag;
}
add_filter( 'script_loader_tag', 'add_defer_attribute', 10, 2 );

Note: If the script tag’s id includes “-js” at the end of the name, it is not necessary to use “-js” in the array.
Example: If script id “jquery-core-js”, use in array “jquery-core”.

PageSpeed Insight Suggestion For WordPress to Eliminate Render Blocking Resources

PageSpeed Insight suggest that deferring non-critical JS or styles. So for this suggestion you can use defer or async methods on JS sources.

Eliminate Render Blocking Resources

Source:

https://stackoverflow.com/questions/70685964/wordpress-script-loader-tag-in-function-php