Skip to content

Instantly share code, notes, and snippets.

@Jany-M
Created August 22, 2018 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Jany-M/f91b0603c90a8b6343e846667591aee4 to your computer and use it in GitHub Desktop.
Save Jany-M/f91b0603c90a8b6343e846667591aee4 to your computer and use it in GitHub Desktop.
[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