Skip to content

Instantly share code, notes, and snippets.

@skipshean
Created August 30, 2018 18:25
Show Gist options
  • Save skipshean/1136c1bc204153ef46255cb1bc852341 to your computer and use it in GitHub Desktop.
Save skipshean/1136c1bc204153ef46255cb1bc852341 to your computer and use it in GitHub Desktop.
Load Wordpress jQuery asynchronously - insert in WP functions.php file
/*Function to defer or asynchronously load scripts*/
function js_async_attr($tag){
# Do not add defer or async attribute to these scripts
$scripts_to_exclude = array('jquery.js', 'script2.js', 'script3.js');
foreach($scripts_to_exclude as $exclude_script){
if(true == strpos($tag, $exclude_script ) )
return $tag;
}
# Defer or async all remaining scripts not excluded above
return str_replace( ' src', ' defer="async" src', $tag );
}
add_filter( 'script_loader_tag', 'js_async_attr', 10 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment