14
function load_my_script(){
wp_register_script( 'my_script', get_template_directory_uri() . '/js/myscript.js', 'jquery' );
wp_enqueue_script( 'my_script', 'jquery');
}
add_action('wp_enqueue_scripts', 'load_my_script');

myscript.js is loading before jquery, why? And how do I make it load AFTER jquery?

Thanks.

2 Answers 2

21

You have a typo in your code. It should be:

function load_my_script(){
    wp_register_script( 
        'my_script', 
        get_template_directory_uri() . '/js/myscript.js', 
        array( 'jquery' )
    );
    wp_enqueue_script( 'my_script' );
}
add_action('wp_enqueue_scripts', 'load_my_script');

The jQuery dependency needs to be an array(), not just a string. This will force your script to load after jQuery.

3
  • ... is 'jquery' needed in wp_enqueue_script?
    – Dave
    Commented Apr 10, 2012 at 17:41
  • In the wp_register_script function, yes. It tells WordPress that jQuery is needed for this script to run, so it'll be loaded accordingly. In wp_enqueue_script it's not necessary, because WP already knows the dependencies from before.
    – swissspidy
    Commented Apr 10, 2012 at 17:56
  • Exactly. Sorry, forgot to remove jQuery from the wp_enqueue_script() call. It's not needed there.
    – EAMann
    Commented Apr 10, 2012 at 17:59
1

get_template_directory_uri() does give you the theme directory, but this is not what you want if you are using a Child Theme.

get_stylesheet_directory_uri() will give your the directory of your "current theme", so in either case, it is safest to use.

2
  • True, but the question is about script dependencies isn't it?
    – Rup
    Commented Mar 18, 2021 at 13:20
  • Yes. But if someone is using a Child Theme, none of these answers will work. So this helps. Commented Mar 19, 2021 at 14:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.