Skip to content

Instantly share code, notes, and snippets.

@fgilio
Created June 19, 2016 20:13
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fgilio/07b042fe15ab1c93fec192bbafd0d0fc to your computer and use it in GitHub Desktop.
Save fgilio/07b042fe15ab1c93fec192bbafd0d0fc to your computer and use it in GitHub Desktop.
Add Defer & Async Attributes to WordPress Scripts
<?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);
@johnakos
Copy link

You've made a mistake on line 14. $defer_script not $async_script :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment