Correct Method to run scripts with dependencies without enqueue?

function script_that_requires_jquery() {
    wp_register_script( 'script-with-dependency', 'http://www.example.com/script-with-dependency.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_script( 'script-with-dependency' );
}
add_action( 'wp_enqueue_scripts', 'script_that_requires_jquery' );

This is the correct method to enqueue scripts (and styles for that matter). You should always be using wp_enqueue_scripts to hook scripts and styles to.

There are a few thing here to check when you register scripts and styles. Firstly, make sure that the order you are placing them inside your function in is correct. The first script in the function will run first, the second second etc.. So, you cannot place your jquery dependant script before jquery, it will not work

The other potential pitfall here is add_action( $hook, $function_to_add, $priority, $accepted_args );. Without setting the $priority parameter, there is always the danger that your script/style will be loaded before other scripts/styles that might overwrite yours.

In your case, your script might be loaded before jquery, so it will not work. I always set this parameter with a very low priority (very high number) when I add custom scripts and styles. This ensures that my scripts and styles loads dead last. So I will do something like this

add_action( 'wp_enqueue_scripts', 'script_that_requires_jquery', 999 );

Leave a Comment