Last active
November 30, 2016 21:20
-
-
Save theJasonJones/403841ce5886ee865ceb686e8d1d5577 to your computer and use it in GitHub Desktop.
Add async or defer to a WordPress script
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
//Enqueue JS like we normally do. | |
function add_test_js_files(){ | |
wp_enqueue_script('script1', '//script1.js?cid=6asdfsdf'); | |
wp_enqueue_script('script2', '//script2.js?cid=a213423423'); | |
} | |
add_action('wp_enqueue_scripts','add_test_js_files'); | |
function add_async_attribute($tag, $handle) { | |
// add script handles to the array below | |
$scripts_to_async = array('script1', 'script2'); | |
//Loop through each file and add the async value | |
// You can switch async to defer here if needed. | |
foreach($scripts_to_async as $async_script) { | |
if ($async_script === $handle) { | |
return str_replace(' src', ' 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