Skip to content

Instantly share code, notes, and snippets.

@ricardobrg
Last active July 18, 2023 09:11
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save ricardobrg/158add836a079a00b46574dbe76c9878 to your computer and use it in GitHub Desktop.
Save ricardobrg/158add836a079a00b46574dbe76c9878 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