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

43 Responses

  1. Lorin Rivers Says:

    It’s amazing that this very cool, very powerful technique is undocumented. I want my money back! Oh wait, it’s free…

    Thanks!

  2. Lorin Rivers Says:

    Oh yeah, one more thing, you can also queue them up by using the function several times in a row, thus:

  3. Firas Says:

    Thanks for the documentation! Incidentally, to get the http wordpress path you’d use get_bloginfo(‘wpurl’) instead of ABSPATH

  4. Nick Ohrn Says:

    @Firas – Thanks for the info. I’m glad I could help in some small way.

  5. Guillaume Says:

    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.

  6. Alejandro Moreno Says:

    @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.

  7. WordPress Plugin Adv Says:

    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.

  8. jameswillisisthebest Says:

    This is my first post
    just saying HI

  9. Owen Cutajar Says:

    @Guillaume: I seem to have the same problem. Have you managed to get to the bottom of it ?

  10. Loading custom Javascript Libraries in Wordpress Themes with wp_enqueue_script() at CGC | Creative Graphics Communications - www.cgandc.net Says:

    [...] 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 [...]

  11. Azizur Rahman Says:

    This also seems to work for Themes and not just Plugins! I have this working for my theme on my site.

  12. Nick Ohrn Says:

    @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.

  13. Rob Says:

    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?

  14. beerfan Says:

    @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.

  15. Idetrorce Says:

    very interesting, but I don’t agree with you
    Idetrorce

  16. Maximus Says:

    I would like to see a continuation of the topic [edit: removed link to an obviously commercial website]

  17. Tassoman Says:

    Please, add ‘jquery’ in the list of js

  18. Nick Ohrn Says:

    @Tassoman,
    Will do.

  19. Simon Says:

    I found this article very helpful. Thanks.

  20. Nick Ohrn Says:

    @Simon,
    Thanks for the feedback :)

  21.   A WordPress Theme Designer’s Wishes and Woes by Free WordPress Themes Blog Says:

    [...] 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 [...]

  22. Wp Wordpress » Blog Archive » A WordPress Theme Designer’s Wishes and Woes Says:

    [...] 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 [...]

  23. Greg Says:

    Thanks, this is just what I was trying to figure out.

  24. Danny Says:

    what’s the calling name for mootools?

  25. Evan Says:

    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!

  26. abubin Says:

    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.

  27. Nick Ohrn Says:

    @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.

  28. Ultra Says:

    Nicely played my friend! Thanks for sharing the infos :-)

  29. Better script loading for WordPress | CrossPixelNation Says:

    [...] 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 [...]

  30. Using jQuery with Wordpress « ammon like salmon Says:

    [...] http://nickohrn.com/loading-javascript-libraries-in-wordpress-plugins-with-wp_enqueue_script/ [...]

  31. Tyler Says:

    Thanks, EXACTLY what I was looking for!

  32. Nick Ohrn Says:

    @Tyler – Great, I’m glad that it could help you out!

  33. Gyroscopic Says:

    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

  34. Nick Ohrn Says:

    @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.

  35. mores Says:

    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

  36. Nick Ohrn Says:

    @mores – Could you email me a code sample – me [at] nickohrn.com

  37. mores Says:

    my email came back, undeliverable.
    Basically, I just have this

    in my header.php right before the wp_head() call.

  38. mores Says:

    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.

  39. Mark Jaquith Says:

    To get the URL of the current plugin’s directory, use plugin_dir_url( __FILE__ )

    It’ll work in more situations.

  40. Nick Ohrn Says:

    Thanks for the tip, Mark.

  41. MyWebmasterTips Says:

    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.

  42. ebflute Says:

    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.

  43. Nick Ohrn Says:

    @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.

Leave a Reply