As we all know, that a website should be fast and responsive to be more user-friendly and SEO friendly.
The most important tool to check site speed is GTmetrix. But almost every time we faced an issue called “Defer parsing of Javascript”.
If you search on Google, you will see different search results are giving different search results and many solutions do not work yet some do work as required to get you the results.
Most people ask you to use ‘defer‘ or ‘async‘ in the script code or possibly you will also get the advice to put all your javascript at the bottom of the page.
But I am going to share the best way to fix that Defer Parsing of JS issue on GTmetrix. This method worked almost every time for me.
You just need to add the below code to your active theme’s functions.php file.
// Defer Javascripts // Defer jQuery Parsing using the HTML5 defer property if (!(is_admin() )) { function defer_parsing_of_js ( $url ) { if ( FALSE === strpos( $url, '.js' ) ) return $url; if ( strpos( $url, 'jquery.js' ) ) return $url; // return "$url' defer "; return "$url' defer onload='"; } add_filter( 'clean_url', 'defer_parsing_of_js', 11, 1 ); }
This code should work for any WordPress website but if the above doesn’t work for some reason, then you can use any of the following codes.
i) You can enable defer parsing for javascript just by adding a ‘defer’ attribute.
<script type="text/javascript" defer="defer" src="your_js_file_source"></script>
ii) In WordPress, All the JavaScript contained in the header wp_head() has to be moved at the end of the page in wp_footer().
To do that, add the below code to your active theme’s functions.php file.
if(!is_admin()) { // Move all JS from header 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); }
That’s it, Enjoy!