Skip to content

Instantly share code, notes, and snippets.

@codescribblr
Forked from ricardobrg/enqueue.php
Last active April 29, 2022 13:16
Show Gist options
  • Save codescribblr/4ff4668db9fb2791180e33566dc90340 to your computer and use it in GitHub Desktop.
Save codescribblr/4ff4668db9fb2791180e33566dc90340 to your computer and use it in GitHub Desktop.
Enqueue scripts in WordPress with defer or async
<?php
// This code is based in Mathew Horne blog post: https://matthewhorne.me/defer-async-wordpress-scripts/
//function to add async attribute
function add_async_attribute( $tag, $handle ) {
$scripts_to_async = array( 'my-js-handle-async', 'another-handle-async' );
//check if this script is in the array
if ( in_array( $handle, $scripts_to_async ) ) {
//return with async
return str_replace( ' src', ' async="async" src', $tag );
} else {
//return without async
return $tag;
}
}
//function to add defer attribute
function add_defer_attribute( $tag, $handle ) {
$scripts_to_defer = array( 'my-js-handle-defer', 'another-handle-defer' );
//check if this script is in the array
if ( in_array( $handle, $scripts_to_defer ) ) {
//return with defer
return str_replace( ' src', ' defer="defer" src', $tag );
} else {
//return without async
return $tag;
}
}
//filter tag
add_filter( 'script_loader_tag', 'add_async_attribute', 10, 2 );
add_filter( 'script_loader_tag', 'add_defer_attribute', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment