How to Defer Parsing JavaScript Files in WordPress?

While checking your site speed on GTMetrix or Google Page Speed, you might ask to use defer method for javascript files.  It has been a hassle for some of the developers as there is no built-in defer solution for WordPress.  Naturally, you have to rely on third party plugins or custom code in order to boost your page speed.

Usually, Javascript files are located in the head section of WordPress website. If you don’t properly defer those scripts on your website, it might cause a slow response to your users and search engines as well.

We can use defer or async to speed up page load times in the browser.

What is the difference between defer and async?

<script async>

async downloads the file during HTML parsing and will pause the HTML parser to execute it when it has finished downloading.

<script defer>

defer downloads the file during HTML parsing and will only execute it after the parser has completed. defer scripts are also guaranteed to execute in the order that they appear in the document.

[source]

 

In this tutorial,  we demonstrating to use defer method using a plugin called W3 Total cache and a custom code hack in your WordPress theme.

Use w3 Total Cache for Defer Parsing

W3 Total Cache plugin has a built-in option for defer Javascript files. We have to just enable it in the setting panel.

Step #1

Go to Performance tab and click on the minify link

How to Defer Parsing JavaScript Files in WordPress

Step #2

Scroll down to JS section and select Non-Blocking using defer both Before <head> and After <body>. Make sure you have enabled the JS minify by ticking the first checkbox in the same screen.

 

How to Defer Parsing JavaScript Files in WordPress

 

Customizing your theme functions

You can do this via customising your theme functions.php.  Open your theme’s functions.php file and add below code to do the defer tag to your Javascript file.

function defer_parsing_of_js ( $url ) {
if ( FALSE === strpos( $url, ‘.js’ ) ) return $url;
if ( strpos( $url, ‘jquery.js’ ) ) return $url;
return “$url’ defer “;
}
add_filter( ‘clean_url’, ‘defer_parsing_of_js’, 11, 1 );

 

Editorial Staff
 

Editorial Staff at tutsplanet is a dedicated team to write various tutorial articles.