I have various javascripts that are necessary plugins in one of my WordPress domains, and I know where in the php file it\'s called from.
I\'m taking every measure I
To gain control over which js files to defer and avoid conflicts you can append a variable to the url in the wp_register_script function like below.
wp_register_script( 'menu', get_template_directory_uri() . '/js/script.js?defer', array('jquery'), '1.0', true );
Then change the line:
if ( FALSE === strpos( $url, '.js' ))
To:
if ( FALSE === strpos( $url, '.js?defer' ))
The new filter looks like this.
add_filter( 'clean_url', function( $url )
{
if ( FALSE === strpos( $url, '.js?defer' ) )
{ // not our file
return $url;
}
// Must be a ', not "!
return "$url' defer='defer";
}, 11, 1 );
Or more universal way:
function add_async_forscript($url)
{
if (strpos($url, '#asyncload')===false)
return $url;
else if (is_admin())
return str_replace('#asyncload', '', $url);
else
return str_replace('#asyncload', '', $url)."' async='async";
}
add_filter('clean_url', 'add_async_forscript', 11, 1);
so you can add async to any script without code changes, just add #asyncload to script url as:
wp_enqueue_script('dcsnt', '/js/jquery.social.media.tabs.1.7.1.min.js#asyncload' )
Another solution using a different filter, which can be used to target a specific script handle:
function frontend_scripts()
{
wp_enqueue_script( 'my-unique-script-handle', 'path/to/my/script.js' );
}
add_action( 'wp_enqueue_scripts', 'frontend_script' );
function make_script_async( $tag, $handle, $src )
{
if ( 'my-unique-script-handle' != $handle ) {
return $tag;
}
return str_replace( '<script', '<script async', $tag );
}
add_filter( 'script_loader_tag', 'make_script_async', 10, 3 );
Something to add the clean_url
filter solution, make sure to validate to use it only on the font-end maybe using if( ! is_admin() ){}
popular plugins like ACF might give you a headache.
Update
Here is my modified version of the solution:
if( ! is_admin() ){
add_filter( 'clean_url', 'so_18944027_front_end_defer', 11, 1 );
function so_18944027_front_end_defer( $url ) {
if ( FALSE === strpos( $url, '.js' ) )
{ // not our file
return $url;
}
// Must be a ', not "!
return "$url' defer='defer";
}
}
Incorporate the async
attribute to the scripts so that they are only loaded once the whole page is loaded
<script type="text/javascript">
function ngfbJavascript( d, s, id, url ) {
var js, ngfb_js = d.getElementsByTagName( s )[0];
if ( d.getElementById( id ) ) return;
js = d.createElement( s );
js.id = id;
js.async = true;
js.src = url;
ngfb_js.parentNode.insertBefore( js, ngfb_js );
};
</script>
Source:Here
A simplified method. Add to your functions.php file to make make JavaScript asynchronous in Wordpress
// Make JavaScript Asynchronous in Wordpress
add_filter( 'script_loader_tag', function ( $tag, $handle ) {
if( is_admin() ) {
return $tag;
}
return str_replace( ' src', ' async src', $tag );
}, 10, 2 );