Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

johnakos commented Oct 19, 2017

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
You can’t perform that action at this time.