Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[WP] Add async, defer and origin attributes to WordPress scripts
<?php
// Place the handles somewhere convenient
global $scripts_to_defer, $scripts_to_async, $scripts_origin;
$scripts_to_defer = array('fancybox_js', 'bootstrap_js');
$scripts_to_async = array('fontawesome_js');
$scripts_origin = array('fontawesome_js');
// Put this in functions.php
function add_defer_attribute($tag, $handle) {
global $scripts_to_defer;
//$scripts_to_defer = array('my-js-handle', 'another-handle');
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);
function add_async_attribute($tag, $handle) {
global $scripts_to_async;
//$scripts_to_async = array('my-js-handle', 'another-handle');
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_async_attribute', 11, 2);
function add_origin_attribute($tag, $handle) {
global $scripts_origin;
//$scripts_origin = array('my-js-handle', 'another-handle');
foreach($scripts_origin as $origin) {
if ($origin === $handle) {
return str_replace(' src', ' origin="anonymous" src', $tag);
}
}
return $tag;
}
add_filter('script_loader_tag', 'add_origin_attribute', 12, 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.