I bet you didn’t know that WordPress already includes several common JavaScript libraries, ready to be called upon with a simple template tag. Libraries such as
- jQuery
- Scriptaculous
- Tiny MCE
- Thickbox
Want to use jQuery in your theme, for a tabbed box, an AJAX something, or some sort of DHTML effect? You can add it in with a single template tag in your header.
<?php wp_enqueue_script('jquery'); ?>
That was easy, wasn’t it? The wp_enqueue_script function can be used in plugins as well, so plugin authors, pleasestop bundling jQuery and Scriptaculous with your plugins. It’s not necessary.
The function can also be used to add your own scripts to a blog (whether you’re doing so from a them or plugin). The syntax is
<?php wp_enqueue_script('handle', 'src', 'dependencies'); ?>
“Handle” is a unique name you give to the script, “src” is the the script’s URL, and the optional last argument allows you to specify dependencies (i.e. scripts that must be loaded before the current one). For example, to load the jQuery UI Tabs package, which naturally requires jQuery, you would use something like this:
<?php wp_enqueue_script('jquery-ui', 'http://example.org/wp-content/themes/my_theme/jquery/jquery-ui-tabs.js', 'jquery'); ?>
The function will also ensure that the same script will not be loaded twice, if I’m not mistaken. Which means if you include jQuery in your theme, and you install a plugin that tries to load jQuery, it will only be loaded once.