-
-
Save joecue/4dca8fe186d2c3c711913ecf27ac9e3a to your computer and use it in GitHub Desktop.
[WP] Add async, defer and origin attributes to WordPress scripts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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