Gauri Chavan
Gauri Chavan

Reputation: 31

Defer parsing of JavaScript: Unable to resolve

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.

Screenshot of GTmetrix report

However, unable to succeed in increasing the Grade for "Defer parsing of Javascript" parameter.

We have tried the following steps on this:

  1. Added the below lines of code to functions.php in /wp-content/themes/"theme"(porto) for our site; which doesn't help.

    // 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
  1. Added the below lines of code to functions.php, but doesn't help.

    // 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 );
}
  1. Tried adding the 'defer="defer"' attribute manually to javascripts in header.php and footer.php, but no change.

  2. 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

Answers (1)

Gauri Chavan
Gauri Chavan

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

Related Questions