Loading WordPress with One jQuery

If there are several plugins on your WordPress sites there may be more than one copy of jQuery, or other script, that’s loaded, especially if you’re relying on the same scripts for control of the site theme as well. Only one copy of each script should be loading up. More than that represents wasted bandwidth for you and wasted time for your site visitors.

To control what scripts are used on your site it may be wise to learn how to disable scripts from loading in the first place. Similar methods can be applied to streamline the number of scripts or stylesheets loaded onto your site.

Check out this great tutorial on disabling scripts and styles. Thanks for sharing, Justin!

You’ll need to modify the functions.php file of your theme to remove styles or scripts. The technique is similar in each case.

  1. Find the ‘handle’ of the script that you’d like to remove.
  2. Pass the script handle to wp_deregister_script().
  3. Wrap one or more ‘deregistrations’ in a new function, like my_deregister_javascript() in this example.
  4. Use add_action() with wp_print_scripts method and add your new function to the functions.php file of your theme.
function my_deregister_javascript() {
  wp_deregister_script('jquery-form');
}
add_action('wp_print_scripts', 'my_deregister_javascript');

From the reference on add_action in the WordPress codex we can see that two arguments are required, namely the $tag or handle of the script and the $function_to_add or the function to which the script is hooked. Two optional parameters can be added to the add_action function to specify the $priority or the order in which the functions are executed, and $accepted_args or the number of arguments that the function accepts. Generically,

add_action( $tag, $function_to_add, $priority, $accepted_args );

In the example above we’ve used ‘wp_print_scripts’ for $tag and ‘my_deregister_javascript’ for $function_to_add while the optional $priority and $accepted_args were not used. This will hook the new function ‘my_deregister_javascript’ to the action called ‘wp_print_scripts’.

Alternatively, a WordPress plugin could be used to manage the scripts and actions called for on your site. Use Google Libraries is a plugin built to detect the scripts needed for a site to run properly, including all the scripts called for by plugins and the active theme. Scripts are loaded in the proper order taking into account dependencies, whether previously known to WordPress or whether provided by the plugin and theme authors. This plugin uses the content delivery network (CDN) of google to supply the most popular javascript libraries, including jQuery and jQuery UI, among others.

WordPress jQuery Loaded in noConflict Mode

Loading JavaScripts in WordPress queues up the internal, minified versions of scripts like jQuery that come with WordPress. jQuery is loaded in noConflict mode so javascript code won’t work if it uses the “$” shortcut like so:

$(document).ready(function(){
  $(.slideshow1).cycle();
});

A simple solution is to pass the dollar sign in the anonymous function of a ready() call and that way the code that you’ve already written with the $ shortcut will work ok. The dollar sign acts as an alias for jquery.

jQuery(document).ready(function($){
.
.
//javascript code in here can use the $() shortcut instead of jQuery()
.
.
});

Alternatively, instead of waiting for the entire document to be rendered as with the ready() method above, the javascript can be put in the following jQuery wrapper so that the code can be used right away.

(function($) {
  	$('#newsticker').innerfade({
	  animationtype: 'slide',
	  speed: 750,
	  timeout: 2000,
	  containerheight: '30px'
	});
})(jQuery);

Using one of these jQuery wrappers is recommended to avoid conflicts with other scripts that may rely on the dollar sign shortcut on your WordPress sites.

Include jQuery or JavaScripts in WordPress

Plugin and theme authors use jQuery for their special effects, but there seems to be some confusion about the proper way to include JavaScript files in WordPress. If you’d like to use jQuery effects on your pages or in your theme, or if you want to include any javascript plugin or personal script, read on to see how to do it properly with WordPress sites.

Queue Up Your Scripts with Actions

Since jQuery itself is already included in the core of WordPress, how should we include a javascript file that we’ve created or even one of the popular jQuery plugins that rely on jQuery? WordPress helps us in this endeavor with a function called ‘wp_enqueue_script()‘ and two actions that are used to call this special function.

The actions are used for either the user side or the admin side, depending on the purpose of your javascript. Use the ‘wp_enqueue_scripts‘ action to call wp_enqueue_script() for use in your themes. If the script functionality is needed on the admin side, use ‘admin_enqueue_scripts‘ action instead.

The format of the wp_enqueue_script() function call is as follows:

wp_enqueue_script('$handle', '$src', '$deps', '$ver', '$in_footer');

where $handle is the name of the script as a lowercase string, $src is the URL to the script, $deps is an array of scripts that the script you’re calling depends on or the scripts that must be loaded first for your script to work, $ver is the script’s version number in string format, and $in_footer is a boolean value to indicate whether the script should be loaded in the <head> or at the end of the <body> in the footer.

The $handle string is the only required parameter, so the other four parameters are optional. The $src, $ver, and $in_footer parameters default values are ‘false’, and $deps defaults to an empty array.

It seems that $src would need to be a required option, but WordPress already knows about several scripts and where to find them. Consult the list of default scripts included with WordPress to pick up their handles.

For example, to queue the jQuery Color plugin, we’d simply use this:

wp_enqueue_script('jquery-color');

To include a script and specify the source, try this for including the jQuery Cycle plugin in the <head>:

wp_enqueue_script('jquery-cycle', 'URL', array('jquery'), '1.3.2');

The URL should not be a hard-coded value for local scripts. Refer to the Function Reference pages in the codex for proper URL formats for plugins and themes.

Register Your Scripts First

Make sure that your scripts are registered first before calling them. Registering a script basically tells WordPress where to find the code for your script. Use the function wp_register_script() to specify the location and handle of your script. The format is similar to the wp_enqueue_script() function:

wp_register_script('$handle', '$src', '$deps', '$ver', '$in_footer');

The parameters have the same meanings and default values as used with wp_enqueue_script(). When in doubt, see what the WordPress Codex has to say about wp_enqueue_script() and wp_register_script().

Create a Function for the Header

Put it all together using wp_register_script(), wp_enqueue_script(), and the appropriate action to call the functions. Create a simple function, like id_scripts() below, and use the add_action() hook to queue up the scripts.

As a side note jQuery itself doesn’t have to be queued via a statement like wp_enqueue_script('jquery');, because it is listed as a dependency of ‘script-alpha‘ in this case.

When enqueuing a custom script that depends on a jQuery plugin, specify jQuery and its plugin in the $deps parameter of the wp_register_script() action for the custom script. For example, if your custom script depends on the jQuery Cycle plugin, which itself depends on jQuery, use array('jquery', 'jquery-cycle') for the $deps parameter. This specifies that both jQuery and its plugin Cycle should be loaded (in that order) before the custom script.

Place this code in the header.php of your theme. Remember, first register the javascript file, then enqueue it and make sure this is done before the wp_head(); statement. Your custom script can then be placed in header.php after the wp_head() call.

Use Theme functions.php to Safely Reference Your Script

When using a child theme take note that the header.php in a child theme will override the default header.php in the parent theme. Instead of placing the script-queuing code in the header, one could more safely put this code in functions.php. The advantage to that way is that the functions.php of a child theme is processed before the functions.php of the parent theme. Both the parent and child theme functions.php are processed, unlike header.php files.

If you’re the least bit unsure about messing with header.php, then just use functions.php to queue up your javascript files. Don’t forget the opening and closing PHP tags in functions.php, else it won’t work. Put the javascript that would come after the wp_head() call in a separate .js file in the child theme and you’re good to go.

Verify that everything is working correctly by viewing the source of the HTML document for a WordPress post that should have the script included. The <script> tags should be visible in the header or in the footer depending on how the scripts were called.

camelCase OK for jQuery

CamelCase refers to a method of combining words into compound words. Instead of using a hyphen to connect two words, camelCase removes the hyphen or space between the words and capitalizes the second word.

jQuery doesn’t mind if you use camelCase when specifying CSS properties, so ‘border-color’ means the same as ‘borderColor’.

The hyphenated property name should always be used in CSS stylesheets, for example, background-color.

.photos 
{
  background-color: #fff;
  color: #000;
}

In jQuery either the hyphenated background-color or camelCase backgroundColor could be used.

$(document).ready(function() {
  $('#b1').animate({
    height: '+=100px',
    backgroundColor: '#eee',
    color:'#2133aa'
  }, 2000, 'linear');
});

Tips:

  1. Single quote marks are needed if the hyphenated property is used, but the non-hyphenated camelCase doesn’t require single quotes around the property name.
  2. The values for each property should be inside single quotes.

Which case you’ll use comes down to personal preference. I like to type fewer quotes and hyphens, so I tend to use camelCase where ever possible.