Powered By Blogger

Wednesday, September 7, 2016

add async or defer keyword in javascript in wordpress function.php

Function.php

function js_async_attr($tag){

# Do not add async to these scripts
$scripts_to_exclude = array('jquery.js', 'sg_popup_core.js', 'jquery-migrate.min.js', 'gravityforms.min.js', 'jquery.qtip.js', 'jquery.json.js', 'custom.js', 'modernizr.custom.js', 'sg_popup_core.js', 'idle-timer.min.js', 'frontend-builder-global-functions.js', 'admin-bar.min.js', 'wp-embed.min.js', 'frontend-builder-scripts.js', 'conditional_logic.min.js', 'placeholders.jquery.min.js', 'jquery.mobile.custom.min.js', 'jquery.fitvids.js');

foreach($scripts_to_exclude as $exclude_script){
if(true == strpos($tag, $exclude_script ) )
return $tag;
}

# Add async to all remaining scripts
return str_replace( ' src', ' async="async" src', $tag );
}
add_filter( 'script_loader_tag', 'js_async_attr', 10 );

No comments:

Post a Comment