Reputation: 31
We are trying to resolve the following output reported on GTmetrix: trying to defer the parsing of javascript in order to decrease the page loading time.
However, unable to succeed in increasing the Grade for "Defer parsing of Javascript" parameter.
We have tried the following steps on this:
// Custom Scripting to Move JavaScript from the Head to the Footer
function remove_head_scripts() {
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_enqueue_scripts', 'remove_head_scripts' );
// END Custom Scripting to Move JavaScript
// 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 );
}
Tried adding the 'defer="defer"' attribute manually to javascripts in header.php and footer.php, but no change.
Installed "Autoptimize" and "WP Deferred Javascripts" Plugins, but this affects the site's working (the dropdown menus do not appear on hover).
Please let us know if there is a way to resolve this, or if is there anything we are missing. Kindly help.
Upvotes: 2
Views: 1513
Reputation: 31
I was able to resolve this by adding the following lines of code to /wp-includes/functions.php
/* Function for defer parsing of javascripts, for loading the website
faster */
function defer_parsing_of_js ( $url )
{
if ( FALSE === strpos( $url, '.js' ) )
return $url;
if ( strpos( $url, 'jquery.js' ) )
return $url;
if ( strpos( $url, 'wp-custom-countdown' ) )
return $url;
return "$url' defer ";
}
add_filter( 'clean_url', 'defer_parsing_of_js', 11, 1 );
Upvotes: 1