I hesitated to ask this question, because it may be too fundamental. However, after digging in to the codex and other topics I became convinced that maybe it is not so fundamental because I could not find an answer to my question.

My question is what purpose does the handle serve in functions like wp_enqueue_script() and wp_enqueue_style()? The codex explains that it is the name of the script or stylesheet, though clearly this does not need to be the name of the file that holds the script or style. I assume that it needs to be unique and I assume that it can be accessed via

global $wp_scripts;

The fact that the handle is explicitly defined suggests that it must have a clear purpose or be re-usable somehow. Otherwise, we would only need to load the script or stylesheet and it would work without the need for a handle. I would appreciate any insights into this.

2 Answers
2

Below is an example of the jquery handle being used in various ways:

// add my js, written in jQuery
// so it requires `jquery.min.js` to be output first
// & say I do this in a early hook like `init`
wp_enqueue_script( 'my-js', 'js.js', array('jquery'));

// later in theme:

// remove WordPress's default jquery,
// change jquery to a specified version, and put in footer
// & say I do this in a later hook like `wp_loaded`
wp_deregister_script( 'jquery' );
wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js', false, '1.8.1', true );
wp_enqueue_script( 'jquery' );
  • Even though I’ve enqued my-js first, I’m able to change and modify jquery

  • I’m able to easily change which jquery version and source I’m using, with ease

  • I have a simple straightforward, pseudocode method to remove a script that I don’t want

  • I changed jquery‘s script, in a big way, but other plugins that rely on jquery will still get jQuery (though the versions might be off, but not important right now)

  • My my-js was done early and is default to be in wp_head. later, I changed jquery to be placed to the footer (import for speed preformace (re: Google PageSpeed). Since my-js depends on jquery, it gets moved down to the footer as well

When you’re dealing with multiple plugin and theme authors, who want to change and modify things, like jQuery, without knowing the dynamic URLs or what other theme/plugin has touched the jquery script — doing anything like this without an handle would be an absolute nightmare.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *