Skip to content

Instantly share code, notes, and snippets.

@xerardoo
Forked from gnikolopoulos/functions.php
Last active September 18, 2015 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xerardoo/0faab36f0ad13a22a24e to your computer and use it in GitHub Desktop.
Save xerardoo/0faab36f0ad13a22a24e to your computer and use it in GitHub Desktop.
Add Defer and Async Attributes to Render Blocking Javascript in WordPress
<?php
function defer_js_async($tag){
// scripts to defer.
$scripts_to_defer = array('script-name1.js', 'script-name2.js', 'script-name3.js');
// scripts to async.
$scripts_to_async = array('script-name1.js', 'script-name2.js', 'script-name3.js');
foreach($scripts_to_defer as $defer_script){
if(true == strpos($tag, $defer_script ) )
return str_replace( ' src', ' defer="defer" src', $tag );
}
foreach($scripts_to_async as $async_script){
if(true == strpos($tag, $async_script ) )
return str_replace( ' src', ' async="async" src', $tag );
}
return $tag;
}
add_filter( 'script_loader_tag', 'defer_js_async', 10 );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment