Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.