WordPress-Christmas-2010-15

Enqueue comment-reply.js – The Right Way

Since Google takes the loading time of a page as a ranking factor, it is always important for a theme designer to incorporate the required resources correctly. In Xtreme One WordPress Framework our JavaScripts are loaded only when they are really needed. Do you have a slider widget on the home page, then the JavaScript for the slider included only on the homepage.

Also including comment-reply.js can be optimized. In the Theme TwentyEleven we can find it in header.php (Line 58):

if ( is_singular() && get_option( 'thread_comments' ) )
	wp_enqueue_script( 'comment-reply' );

That means, if "Enable threaded (nested) comments" in the Discussion Settings is activated and if it's on a single page, then load the script comments-reply.js.
But we also don't need the script on pages where there is no comment form and not on the homepage if it's a page. Neither do we need the script if comments are closed or not allowed.
Or easier to say: We only need it, if "Enable threaded comments" is activated and a comment form is displayed.

Using the example of TwentyEleven I show now how to do it better. First, we delete from the header.php the lines

if ( is_singular() && get_option( 'thread_comments' ) )
	wp_enqueue_script( 'comment-reply' );

In the functions.php we implement the enqueue function of the script

function xtreme_enqueue_comments_reply() {
	if( get_option( 'thread_comments' ) )  {
		wp_enqueue_script( 'comment-reply' );
	}
}

Now we get to the important part. We add to the function twentyeleven_setup() this line:

add_action( 'comment_form_before', 'xtreme_enqueue_comments_reply' );

The Hook comment_form_before is only there when the comment form is loaded and we are adding the enqueue function for the script. A positive side effect, the script is now loaded at the end of the document and does not hinder the loading of the site.
At best, you create a Child Theme, so the changes are protected against overwriting when you update WordPress the next time. Maybe the WordPress Dev team will use this approach in a future version of their default Theme TwentyEleven.

Comments are closed.

3 comments

  1. Markus

    translate to en 🙂

    "In die functions.php schreiben wir die Funktion zum Einbinden des Scripts"

    grüsse

  2. Tom J Nowell

    Interesting, although you forgot to translate one part:

    "In die functions.php schreiben wir die Funktion zum Einbinden des Scripts"

  3. Michael

    @Markus @Tom Sorry, fixed now 🙂