I was wondering if, after registering a scripts and specifying a dependency, upon enqueuing it, should you specify the dependency again?
By that good\'ol
No, you don't need to specify the dependencies twice.
To understand why the option is there, you need to look at what wp_enqueue_script
and wp_register_script
are for.
You don't have to register the script at all before you enqueue it, you can just use wp_enqueue_script
on its own and it will register it if its not already registered - this is why you have the same options (including setting the dependencies) in both functions.
For example you can have this in your functions.php ad it will both register and enqueue the scripts at the same time:
add_action( 'wp_enqueue_scripts', 'theme_scripts' );
function theme_scripts() {
if( ! is_admin() ) {
wp_enqueue_script( 'script_1_js', '//path/to/script/one.js' );
wp_enqueue_script( 'script_2_js', '//path/to/script/two.js', array( 'script_1_js' ) );
}
}
Why bother registering a script then? There are a number of advantages, such as:
wp_enqueue_script
function for that script.For example you can have this in your functions.php:
add_action( 'wp_enqueue_scripts', 'theme_scripts' );
function theme_scripts() {
if( ! is_admin() ) {
wp_register_script( 'script_1_js', '//path/to/script/one.js' );
wp_register_script( 'script_2_js', '//path/to/script/two.js', array( 'script_1_js' ), '1.1', true );
}
}
Now if you only need to load script_two_js
in 2 particular page templates for example, you can add wp_enqueue_script( 'script_1_js' );
into to those templates without having to add the dependencies, version every time, because it already knows this from when it was registered.
wp_register_script
, and if you have another script have have this script in its dependencies, then it will automatically get loaded before that script without the need to enqueue it.For example, if you have four.js which depends on 3 other scripts, e.g.
add_action( 'wp_enqueue_scripts', 'theme_scripts' );
function theme_scripts() {
if( ! is_admin() ) {
wp_register_script( 'script_1_js', '//path/to/script/one.js' );
wp_register_script( 'script_2_js', '//path/to/script/two.js' );
wp_register_script( 'script_3_js', '//path/to/script/three.js' );
wp_register_script( 'script_4_js', '//path/to/script/four.js', array( 'script_1_js', 'script_2_js', 'script_3_js' );
}
}
Now you can load the script with wp_enqueue_script( 'script_4_js' );
at it will automatically load scripts one, two and three.
Hope this helps answer your question!