Skip to content

Instantly share code, notes, and snippets.

@tyohan
Created November 14, 2017 07:57
Show Gist options
  • Save tyohan/27a622ce9c54d436cf9f1919654fd545 to your computer and use it in GitHub Desktop.
Save tyohan/27a622ce9c54d436cf9f1919654fd545 to your computer and use it in GitHub Desktop.
Functions to make scripts async and defer on WordPress Seventeen Theme
function add_defer_attribute($tag, $handle) {
// add script handles to the array below
$scripts_to_defer = array(
'html5',
'jquery',
'jquery-migrate',
'wp-embed',
'twentyseventeen-skip-link-focus-fix',
'jquery-scrollto',
'twentyseventeen-global',
'twentyseventeen-navigation',
'comment-reply');
foreach($scripts_to_defer as $defer_script) {
if ($defer_script === $handle) {
return str_replace(' src', ' defer="defer" src', $tag);
}
}
return $tag;
}
function add_async_attribute($tag, $handle) {
// add script handles to the array below
$scripts_to_async = array(
'jquery',
'jquery-core',
);
foreach($scripts_to_async as $async_script) {
if ($async_script === $handle) {
return str_replace(' src', ' async="async" src', $tag);
}
}
return $tag;
}
add_filter('script_loader_tag', 'add_defer_attribute', 10, 2);
add_filter('script_loader_tag', 'add_async_attribute', 10, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment