Skip to content

Instantly share code, notes, and snippets.

@00face
Forked from ricardobrg/enqueue.php
Last active August 4, 2021 17:35
Show Gist options
  • Save 00face/50a65e51cf57128ca99a6809703e6c37 to your computer and use it in GitHub Desktop.
Save 00face/50a65e51cf57128ca99a6809703e6c37 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/ &
// Ricardo Gonçalves https://gist.github.com/ricardobrg/158add836a079a00b46574dbe76c9878
//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