How-To: Load JavaScript Libraries in WordPress
Note: This is a modified version of my original post. A lot has changed since this was first written, and this is my second most popular blog page. As such, I’ve edited it to make certain that it is as up to date as possible.
Almost every plugin that I’ve written has some type of JavaScript in it. I generally separate all the JavaScript that I can out of pages that I expect to be displayed and include it in separate file(s). In WordPress, there is a right way and a wrong way to make sure these external files are linked to from the page being displayed. In this post, I’ll show you the right way to do things, and then expand on that by showing you what WordPress has out of the box for you to use.
WordPress Functions of Interest
WordPress has two particular functions of interest in this discussion. The first is wp_register_script. Its signature is as follows:
wp_register_script( $handle, $src, $dep = array(), $ver = false );
wp_register_script adds a new JavaScript file to a list of those that are recognized by WordPress. It will not cause the script to be displayed in output, but that’s what the next function is for. Also note that the variable $src must be a absolute URL path and not a server folder path. The server folder path won’t work here.
The next function of interest is wp_enqueue_script. Its signature is as follows:
wp_enqueue_script( $handle, $src = false, $deps = array(), $ver = false );
When you need to make sure that WordPress outputs an appropriate script tag, this is the function you use. Notice that $src is a optional argument. If the script has previously been registered with WordPress via wp_enqueue_script, you need pass only the handle because the source of the file is already known.
Now, that all leads us to a couple of questions. What are the benefits of these two functions? How do you use them? What scripts are already available?
Benefits
The main benefit of using wp_register_script and wp_enqueue_script is that you won’t have script collisions like you could if you linked to the the script files manually.
Also, if you were observant you noticed the $deps variable in both function signatures above. This denotes what other JavaScript your file relies on. If you need jQuery to be loaded for your JavaScript to work, you could do the following.
wp_register_script( 'my-handle', 'http://example.com', array( 'jquery' ) );
There is another distinct benefit to using wp_register_script. Say you are developing a plugin which adds multiple pages to the administrative and frontend interface. You have developed a custom JavaScript file that makes everything work, and you need to include it in these various places. You would register the script once, probably when your plugin is initialized, and then just enqueue it whenever you need to throughout your plugin.
Usage
I’m going to provide a very simple example below. This is a full plugin, but it doesn’t really do anything since some dependencies are missing (like the JavaScript file).
class Test_Enqueue {
/**
* Adds action and filter hooks and registers our custom javascript file.
*
*/
function __construct() {
add_action( 'admin_head', array( &$this, 'on_admin_head' ) );
wp_register_script(
'enqueue-test',
plugin_dir_url( __FILE__ ) . '/enqueue-test.js',
array( 'jquery' )
);
}
/**
* Enqueues the necessary javascript file if this is the Write Page interface.
*
*/
function on_admin_head() {
if( 'page.php' == basename( $_SERVER[ 'REQUEST_URI' ] ) ) {
wp_register_script( 'enqueue-test' );
}
}
}
Pre-Registered Scripts
WordPress provides a ton of pre-registered scripts right out of the box. Here is a complete listing of them as of WordPress 2.6.1. The following scripts can be used anywhere:
- common
- sack
- quicktags
- colorpicker
- editor
- editor_functions
- tiny_mce
- prototype
- wp-ajax-response
- autosave
- wp-lists
- scriptaculous-root
- scriptaculous-builder
- scriptaculous-dragdrop
- scriptaculous-effects
- scriptaculous-slider
- scriptaculous-sound
- scriptaculous-controls
- scriptaculous
- cropper
- jquery
- jquery-form
- jquery-color
- interface
- suggest
- schedule
- thickbox
- swfupload
- swfupload-degrade
- swfupload-queue
- swfupload-handlers
- jquery-ui-core
- jquery-ui-tabs
- jquery-ui-sortable
The following scripts can only be used in the administrative area.
- ajaxcat
- admin-categories
- admin-tags
- admin-custom-fields
- password-strength-meter
- admin-comments
- admin-users
- admin-forms
- xfn
- upload
- postbox
- slug
- post
- page
- link
- comment
- admin-gallery
- media-upload
- admin-widgets
- word-count
- wp-gears
- theme-preview
April 18th, 2007
It’s amazing that this very cool, very powerful technique is undocumented. I want my money back! Oh wait, it’s free…
Thanks!
April 18th, 2007
Oh yeah, one more thing, you can also queue them up by using the function several times in a row, thus:
June 8th, 2007
Thanks for the documentation! Incidentally, to get the http wordpress path you’d use get_bloginfo(‘wpurl’) instead of ABSPATH
June 9th, 2007
@Firas – Thanks for the info. I’m glad I could help in some small way.
June 18th, 2007
I use add_action(‘wp_head’, ‘myFunction’) to load some stuff in the portion of the web page.
That function prints some stuff then calls wp_enqueue_script. The code is printed fine, but the “enqueued scripts” are not loaded. When I move out of the function (outside of any function), it works fine.
I looked at the code and don’t understand why this is not working.
July 4th, 2007
@Guillaume:
This guy
(http://zeo.unic.net.my/notes/lightbox2-for-wordpress/)
adds his wp_enqueue_script to the init() action. But I haven’t tested it.
August 4th, 2007
It is pity that such a wealth of information is not available from wordpress.org. I wish someone who has proper knowledge should go and fill that in.
I wish I had a better understanding of a number of API’s in wordpress. I see one of the most important query_posts is not documented properly. This wp_enque_script is another example.
September 8th, 2007
This is my first post
just saying HI
September 17th, 2007
@Guillaume: I seem to have the same problem. Have you managed to get to the bottom of it ?
September 18th, 2007
[...] reading Nick’s entry on Loading Javascript Libraries in Wordpress Plugins, I have decided to use the same techniques to get my custom Theme to load JavaScript using [...]
September 18th, 2007
This also seems to work for Themes and not just Plugins! I have this working for my theme on my site.
September 18th, 2007
@Azizur – That’s great! I’m glad this worked for you and I was able to contribute in some small part to the WordPress community.
November 4th, 2007
I am desperately seeking a solution to this. I cannot load my own version of jqeury, this is my first time making a plugin and I must have jacked about 10 plugin’s codes for loading javascript into the head and NONE work what the hell is the problem? When I view the source it shows the exact same route and path it would be as if I manually put it into header.php. I even tried the above method with enqueue script however when I attempt to supply my own name and path for it and put ‘jquery’ it decides to grab its own, anyone have a solution for this?
November 29th, 2007
@Guillaume, @Owen,
Calling wp_enqueue_script() in a “wp_head” action doesn’t work because wp_head happens after scripts are queued and processed. Placing it in a “init” action would work if you also want the script to be added to public pages, since init is called for every page. Placing it in a “admin_menu” action, as the article describes, resolves both issues.
December 15th, 2007
very interesting, but I don’t agree with you
Idetrorce
December 20th, 2007
I would like to see a continuation of the topic [edit: removed link to an obviously commercial website]
January 2nd, 2008
Please, add ‘jquery’ in the list of js
January 2nd, 2008
@Tassoman,
Will do.
January 16th, 2008
I found this article very helpful. Thanks.
January 16th, 2008
@Simon,
Thanks for the feedback :)
February 25th, 2008
[...] it in themes and plugins. This applies to every other JavaScript library in that folder as well. Reusing those files in themes and plugins can be done, but I’ve tried several times and ultimately can’t get it to work. Perhaps an official [...]
February 25th, 2008
[...] it in themes and plugins. This applies to every other JavaScript library in that folder as well. Reusing those files in themes and plugins can be done, but I’ve tried several times and ultimately can’t get it to work. Perhaps an official [...]
March 3rd, 2008
Thanks, this is just what I was trying to figure out.
March 14th, 2008
what’s the calling name for mootools?
April 12th, 2008
THANKS for this doc!
Although it doesn’t help with my current project, and I was only led here on a tangent investigation, it was very well written and I’m sure it will come in handy sometime!
Cheers!
July 3rd, 2008
add the wp_enqueue_script() to where in the codes? Anywhere? header? wp loop?
I tried adding to my page file and it doesn’t work.
July 3rd, 2008
@abubin – You would need to use wp_enqueue_script somewhere before the header is being added. You could put it at the top of your header.php file if you wanted, probably.
July 20th, 2008
Nicely played my friend! Thanks for sharing the infos :-)
August 19th, 2008
[...] has a whole folder of plug-and-play libraries that are just waiting to be included with the wp_enqueue_script function. Toss it in your functions.php file and it will inject the scripts into wp_head(). You can [...]
October 14th, 2008
[...] http://nickohrn.com/loading-javascript-libraries-in-wordpress-plugins-with-wp_enqueue_script/ [...]
October 24th, 2008
Thanks, EXACTLY what I was looking for!
October 24th, 2008
@Tyler – Great, I’m glad that it could help you out!
June 10th, 2009
Hi Nick, great post!
However, I’m pretty new to WordPress and am not sure how to include this in a theme I have. Is there any more specific info to be had? You mention putting the wp_enqueue_script() in an init function but where is that?
I read above that Azizur Rahman managed to get it working in a theme, any chance of a post detailing exaclty how you did that please?
Cheers, Gyro
June 10th, 2009
@Gyroscopic – To use wp_enqueue_script ( or wp_enqueue_style ) in a theme, you just have to make sure you call that function before wp_head(). You could also put the function call in your theme’s functions.php file.
August 27th, 2009
Thanks for the info. I managed to get jquery to load, but the other files refuse to load. I need jquery-color too, and neither placing the code in header.php nor in functions.php will load jquery-color. Any ideas?
WP 2.8.4, btw
August 27th, 2009
@mores – Could you email me a code sample – me [at] nickohrn.com
August 28th, 2009
my email came back, undeliverable.
Basically, I just have this
in my header.php right before the wp_head() call.
August 28th, 2009
Update: the strange thing is, when I add ONLY
wp_enqueue_script(‘jquery-color’)
, it still loads jquery. Not the color plugin, but jQuery itself.
Strange, strange.
September 8th, 2009
To get the URL of the current plugin’s directory, use
plugin_dir_url( __FILE__ )It’ll work in more situations.
September 8th, 2009
Thanks for the tip, Mark.
September 27th, 2009
Great information man, I finally know that I just simply need to use the wp_enqueue command to get my javascript file to work properly.
September 28th, 2009
Can you explain the handle and what it is? is it something you define when you register the script and then you can use it later in the enqueue script? I simply want to include the custom jquery script so that I can use it in one place on my custom page within wordpress (it is a fading effect I want to use in my home page). I don’t need to use it in a plugin.
September 29th, 2009
@ebflute – The handle is just used in wp_enqueue_script if you’ve previously registered it. By default, WordPress registers a bunch of scripts “out of the box”, like jQuery and more. You can then enqueue them by just passing the handle.