When should I use wp_register_script() with wp_enqueue_script() vs just wp_enqueue_script()?

I’m having trouble understanding when you need to use wp_register_script(). Currently, I just use something like:

add_action( 'admin_enqueue_scripts', array( $this, 'enqueue' ) );
function enqueue() {
    $handle="some-handle";
    $js="http://example.com/my.js";
    wp_register_script( $handle, $js );
    wp_enqueue_script( $handle );
}

I’ve done a lot of reading (Codex, blogs, etc.), but can’t quite understand when I should register first, or when I should just enqueue. As an example, I noticed TwentyTwelve doesn’t register any styles or scripts, it just enqueues them.

3

The wp_register_script() Codex page literally says:

A safe way of registering javascripts in WordPress for later use with wp_enqueue_script().

This means, if you want to register your scripts, but not directly load them in your pages, you can register the files once, and then load them when you need them.

For example:

You have a switch statement wich loads some functionality, but two of three cases needs a particular javascript file, and one doesn’t. You can enqueue the script every time, wich costs more resources, or just enqueue the script when you need it:

...
wp_register_script( 'my-handy-javascript', ... );
...
switch( $somevar ) {
    case 'value':
        wp_enqueue_script( 'my-handy-javascript' ); // needs the file
        ...
    break;
    case 'value2':
        wp_enqueue_script( 'my-handy-javascript' ); // needs the file
        ...
    break;
    default:
    case 'value3': // doesn't needs the file
        ...
    break;
}

It is not necessary to register a script and then enqueue them, but it can provide some logic in your code if you register all the scripts you need somewhere in your functions.php instead of everywhere in your code.

The Codex also tells the following:

Use the wp_enqueue_scripts action to call this function, or admin_enqueue_scripts to call it on the admin side.

This means that if you want to enqueue your script on the frond-end and in the back-end, you can register a script once, and then load it on the front-end with wp_enqueue_script and in the back-end with admin_enqueue_script.
This way you won’t have the same enqueue recourse twice in one theme, plugin, widget or whatever.

Leave a Comment