Skip to content

Instantly share code, notes, and snippets.

@ckschmieder
Created February 16, 2018 02:40
Show Gist options
  • Save ckschmieder/36f293435b0acf38303c5ffa61b5891c to your computer and use it in GitHub Desktop.
Save ckschmieder/36f293435b0acf38303c5ffa61b5891c to your computer and use it in GitHub Desktop.
Have a WordPress site with some render blocking JavaScript? Are you using a plugin like Autoptimize that can’t aggregate/concatenate and therefore cannot defer external, 3rd-party JavaScript? Eliminate it with this code snippet for better real world performance and better grades on tools like PageSpeed Insights! Copy and paste this code snippet …
/*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('script1.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="defer" src', $tag );
}
add_filter( 'script_loader_tag', 'js_async_attr', 10 );
@ckschmieder
Copy link
Author

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