Skip to content

Instantly share code, notes, and snippets.

@pagelab
Created June 2, 2017 17:42
Show Gist options
  • Save pagelab/17586d8d320a314ad86bd03a8717966f to your computer and use it in GitHub Desktop.
Save pagelab/17586d8d320a314ad86bd03a8717966f to your computer and use it in GitHub Desktop.
WordPress: add defer and async to selected scripts via script_loader_tag
<?php
/**
*
* Add defer and async to selected scripts
*
* @author Matthew Horne
* @link https://matthewhorne.me/defer-async-wordpress-scripts/
*/
add_filter('script_loader_tag', 'prefix_add_defer_attribute', 10, 2);
add_filter('script_loader_tag', 'prefix_add_async_attribute', 10, 2);
function prefix_add_defer_attribute($tag, $handle) {
// add script handles to the array below
$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;
}
function prefix_add_async_attribute($tag, $handle) {
// add script handles to the array below
$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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment