Move jQuery to the Bottom in WordPress

By default, jQuery is registered by WordPress to appear in the head if it’s needed by a theme. Good performance techniques say JavaScript scripts should appear at the bottom of the page so that they don’t block other downloads while they are being parsed. The following moves it from the head, to the bottom, just before the closing body tag:

add_action( 'init', 'gamajo_move_jquery_register' );
/**
 * Push jQuery to the bottom of the source.
 *
 * Read the caveat on the tutorial.
 * @author Gary Jones
 * @link http://code.garyjones.co.uk/move-jquery-to-wordpress-bottom/
 */
function gamajo_move_jquery_register() {
	if ( !is_admin() ) {
		wp_deregister_script( 'jquery' );
		wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', false, '1.4.4', true );
	}
}

That final true value tells WordPress to shift it to the bottom if possible.

Caveat

Be aware, that this can break your site! Any plugins that rely on jQuery have three ways of causing mischief if the reference to the jQuery library isn’t where they think it is.

  • They correctly use wp_enqueue_script() to reference jQuery as a pre-requisite, which then moves it to the head, and works fine.
  • They don’t use the wp_enqueue_script() function, add their own call to jQuery. This then gives two version of the libraries loading, possibly giving duplicate function name errors, or at least loading one unnecessarily.
  • They add in inline jQuery code, with no check for the jQuery library already being referenced, which then causes JavaScript errors

So, while this may add a very small performance benefit, it may also mean badly coded plugins break and won’t work until you undo the optimisation.

Speak Your Mind

*