If you are trying to optimize and speed up your WordPress website, you are probably aware of Google’s PageSpeed Tool.

With PageSpeed Insights you can identify ways to make your site faster and more mobile-friendly, but a common headache for many WordPress website owners is looking for a way to fix: “Eliminate render-blocking JavaScript”.

Here’s a very simple solution you can apply. Each WordPress theme has a functions.php file. Copy and paste the following snippets at the bottom of functions.php file:

/* main function */
function js_async_attr($tag){

# Except jquery
$scripts_to_exclude = array('jquery.js');

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

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

That’s all you have to do! However, please note that you will not get rid of the alert: Eliminate render-blocking JavaScript because we still have one script left jquery.js from being executed asynchronously on purpose. This is our safe recommendation in order to avoid breaking the functionality of your website:

pagespeedgoogle

Important: Clear cache before running a new page speed test! PageSpeed Insights should see any changes you’ve made within a few minutes, but from my own experience it is not always like that. So if you do not see the expected changes right away, just try again later. Also, this change alone may not result in a significant change in your page speed score. If you have any questions, please, leave a comment and I’ll assist you!

Just a final note for developers

As explained, all scripts will now be executed asynchronously, except jquery.js. But if for any reason you want even more scripts ignored, simply add them to $scripts_to_exclude as shown below (in our example jquery.js and jquery-migrate.min.js scripts are excluded) :

/* main function */
function js_async_attr($tag){

# Except jquery and jquery migrate
$scripts_to_exclude = array('jquery.js','jquery-migrate.min.js');

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

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

Tutorials Wordpress Tutorials

You may also like:

We create themes & templates
Take a look at our
newest themes

Bizconstruct - New Theme Release

Latest WordPress Theme Updates

  Keep an eye on what we're doing  
 
    Find us:      

Keep an eye on what we're doing