function add_defer_attribute($tag, $handle) {
// Add the handles of the scripts you want to defer or async in the array below
$scripts_to_defer = array('script-handle1', 'script-handle2');
foreach ($scripts_to_defer as $defer_script) {
if ($defer_script === $handle) {
return str_replace(' src', ' defer="defer" src', $tag);
}
}
return $tag;
}
add_filter('script_loader_tag', 'add_defer_attribute', 10, 2);