ASYNC JS in WordPress

/*function to add async and defer attributes*/
function defer_js_async($tag){

## 1: list of scripts to defer.
//$scripts_to_defer = array('script-name1.js', 'script-name2.js', 'script-name3.js');
## 2: list of scripts to async.
$scripts_to_async = array('plugins/easing-slider/js/jquery.easingslider.min.js', 'jquery/jquery-migrate.min.js', 'plugins/tubepress/src/main/web/js/tubepress.js','plugins/google-map-shortcode/js/gmshc.2.3.min.js','plugins/youtube-embed-plus/scripts/ytprefs.min.js');

#defer scripts
foreach($scripts_to_defer as $defer_script){
if(true == strpos($tag, $defer_script ) )
return str_replace( ' src', ' defer="defer" src', $tag );
}
#async scripts
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 );
Scroll to Top