0

I added my several javascript files manually in the header in the early stages of development and everything was working. Then I decided to use the enqueue scripts function in functions.php to enqueue them instead. This led to jQuery giving the $ is not a function error. That led me to putting this code in each of my JavaScript files (wrapping the code inside):

jQuery.noConflict();
jQuery( document ).ready(function( $ ) {
  // Code that uses jQuery's $ can follow here.
});
// Code that uses other library's $ can follow here.

After that jQuery started working, but now I'm getting the order of things wrong and other functions end up not being defined. I'm attempting to put in the correct dependencies for each script, but somehow the dependencies don't seem to be working. It seems like the document ready function might be somehow overriding or otherwise messing with the dependencies. If I get rid of the document ready scripts in most of my files and replace $ with jQuery then everything starts working.

This is how my enqueue scripts function looks like in functions.php:

function theme_scripts() {
    global $current_user; //for sending the logged in user info to a js file
    $current_user = wp_get_current_user();
 
    wp_enqueue_script( 'jqueryNew', get_template_directory_uri() . '/js/jquery-3.4.1.min.js', '', '', false );
    wp_enqueue_script( 'getRecipe', get_template_directory_uri() . '/js/getRecipe.js', array( 'jqueryNew' ), '', false );
    wp_localize_script( 'getRecipe', 'theUser', array (
       'username' => $current_user->user_login, ) );
    wp_enqueue_script( 'writeRecipe', get_template_directory_uri() . '/js/writeRecipe.js', array( 'jqueryNew' ), '', false );
    wp_enqueue_script( 'getFood', get_template_directory_uri() . '/js/getFood.js', array( 'jqueryNew' ), '', false );
    wp_enqueue_script( 'setRecipe', get_template_directory_uri() . '/js/setRecipe.js', array( 'jqueryNew' ), '', false );
    wp_enqueue_script( 'getRecipeDetails', get_template_directory_uri() . '/js/getRecipeDetails.js', array( 'jqueryNew' ), '', false );
    wp_enqueue_script( 'handleEvents', get_template_directory_uri() . '/js/handleEvents.js', array( 'jqueryNew', 'getRecipe', 'writeRecipe' ), '', false );
    
 }
 add_action( 'wp_enqueue_scripts', 'theme_scripts' );

My question is this: How can I use enqueue scripts with several javascript files while also using $ to refer to jQuery, without messing the order of things up because of various document ready calls?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.