Created
June 19, 2016 20:13
-
-
Save fgilio/07b042fe15ab1c93fec192bbafd0d0fc to your computer and use it in GitHub Desktop.
Add Defer & Async 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 | |
/** | |
* Add Defer & Async Attributes to WordPress Scripts | |
* @author Matthew Horne - http://matthewhorne.me/defer-async-wordpress-scripts/ | |
*/ | |
/** | |
* Defer | |
*/ | |
function add_defer_attribute($tag, $handle) { | |
$scripts_to_defer = array('my-js-handle', 'another-handle'); | |
foreach($scripts_to_defer as $defer_script) { | |
if ($async_script !== $handle) return $tag; | |
return str_replace(' src', ' defer="defer" src', $tag); | |
} | |
return $tag; | |
} | |
add_filter('script_loader_tag', 'add_defer_attribute', 10, 2); | |
/** | |
* Async | |
*/ | |
function add_async_attribute($tag, $handle) { | |
$scripts_to_async = array('my-js-handle', 'another-handle'); | |
foreach($scripts_to_async as $async_script) { | |
if ($async_script !== $handle) return $tag; | |
return str_replace(' src', ' async="async" src', $tag); | |
} | |
return $tag; | |
} | |
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
You've made a mistake on line 14. $defer_script not $async_script :)