The Right Way to Use JavaScript in Your WordPress Plugin

Ozh explains how to properly use JavaScript in your WordPress plugins. There are two key parts:

  1. Use wp_enqueue_script() to load external libraries and standalone scripts, instead of generating your own script header tags.
  2. On admin pages, use the admin_print_scripts-[mypage] action hook to register the code on only your plugin’s page, not every admin page.

Both of those techniques have been available since WordPress 2.1, so plugin authors can be pretty confident that there will be no backwards-compatibility issues in employing them. (Despite the fact that WordPress is maintaining the 2.0.x version line until 2010, my research suggests that the number of users of that branch is insignificant.)

I would add one more tip to Ozh’s: don’t pollute the global JavaScript namespace, especially with the over-used “$”. A number of JavaScript libraries use the dollar sign in different ways, so you can run into problems if, for example, you’re using jQuery but another plugin has loaded Prototype.

Fortunately, jQuery makes it easy to use “$” in a friendly way with other libraries. My favorite is to wrap jQuery-based code in something like the following, which employs $ outside of the global namespace and waits to execute the script until after the DOM has loaded.

jQuery(function($) { /* some code that uses $ */ });

One Trackback

  1. […] The Right Way to Use JavaScript in Your WordPress Plugin […]

One Comment

  1. Posted April 11, 2008 at 11:05 am | Permalink
    Austin Matzko

    As Otto pointed out on the WordPress hackers list, you can also use "load-" . [mypage] to enqueue the script only on one’s plugin page.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*