Last active
July 18, 2023 09:11
-
-
Save ricardobrg/158add836a079a00b46574dbe76c9878 to your computer and use it in GitHub Desktop.
Enqueue scripts in WordPress with defer or async
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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