After running my Wordpress site through Page Speed Insights I'm told that I need to eliminate render blocking javascript. So I have moved the vast majority of javascript to just before the closing body tag but the warning still appears in Page Speed Insights.
Can anyone suggest what I can do to resolve this issue please?
The site is /
Thanks in advance
After running my Wordpress site through Page Speed Insights I'm told that I need to eliminate render blocking javascript. So I have moved the vast majority of javascript to just before the closing body tag but the warning still appears in Page Speed Insights.
Can anyone suggest what I can do to resolve this issue please?
The site is http://www.stewartandsonsroofingliverpool.co.uk/
Thanks in advance
You can install a plugin to load your JavaScript asynchronously or try to do it manually adding code to your functions.php
to load your scripts asynchronously.
This can get you started,
Warning
loading JavaScript asynchronously will cause several issues with dependencies:
/*function to add async to all scripts*/
function js_async_attr($tag){
//Add async to all scripts tags
return str_replace( ' src', ' async="async" src', $tag );
}
add_filter( 'script_loader_tag', 'js_async_attr', 10 );
so you have to check your JS code and update it.
defer
attributeInstead of converting all script to async
as this answer suggested, it's better to use defer
. That way, you'll not have dependency errors.
For example, you use a custom script and that script depends on jQuery
. Since jQuery
is more likely to be bigger than your custom script, it'll probably end loading before jQuery
, so your CODE will behave unpredictably.
Instead you can use the following CODE to make sure dependency works:
function js_defer_attr( $tag ){
// add defer to all scripts tags
return str_replace( ' src', ' defer="defer" src', $tag );
}
add_filter( 'script_loader_tag', 'js_defer_attr', 10 );
Here's more about the defer
attribute.
It's also possible to replace all scripts to footer. Use the following CODE (instead of the above) to place all scripts in the footer:
function move_scripts_to_footer() {
remove_action( 'wp_head', 'wp_print_scripts' );
remove_action( 'wp_head', 'wp_print_head_scripts', 9 );
remove_action( 'wp_head', 'wp_enqueue_scripts', 1 );
add_action( 'wp_footer', 'wp_print_scripts', 5 );
add_action( 'wp_footer', 'wp_enqueue_scripts', 5 );
add_action( 'wp_footer', 'wp_print_head_scripts', 5 );
}
add_action( 'wp_head', 'move_scripts_to_footer', -1 );
You can eliminate render blocking JavaScript very easily by using different plugins, like Autoptimize. Follow these steps:
You can also use W3 Total Cache plugin to solve the issue. You will find the steps for applying it right here.