jQuery is not defined in Wordpress, but my script is enqueued properly

后端 未结 5 761
别跟我提以往
别跟我提以往 2020-12-31 02:19

I am trying to load a separate javascript file mobile-menu.js to my Wordpress theme. When I look at the console, it says, \"jQuery is not defined.\" However, I know that I e

相关标签:
5条回答
  • 2020-12-31 02:34

    First Make sure that jquery file is include in the header, and your file requied jQuery

    wp_enqueue_script( 
            'lapetitefrog-mobile-menu', 
            get_template_directory_uri() . '/js/mobile-menu.js', 
            array('jquery'), 
            '1.0', 
            true 
    );
    

    Second you should start your javascript file like:

    (function($) {
        $(document).ready(function() {
            .......
        });
    })(jQuery);
    

    OR

    // Use jQuery in place of $
    jQuery(document).ready(function() {
        .....
    });
    
    0 讨论(0)
  • 2020-12-31 02:37

    Wordpress ships with jQuery by default

    // Adds jQuery
        add_action('init', 'childoftwentyeleven_down');
    
            function childoftwentyeleven_down() {
    
              // register your script location, dependencies and version
                    wp_register_script('down',
                        get_stylesheet_directory_uri() . '/js/down.js',
                        array('jquery') );
               // enqueue the script
               wp_enqueue_script('down');
    
            }
    
    0 讨论(0)
  • 2020-12-31 02:41

    Add wp_enqueue_script('jquery'); before you enqueue your scripts. 

    0 讨论(0)
  • 2020-12-31 02:46

    You can try:

    enqueue Jquery first.

    wp_enqueue_script('jquery'); 
    

    and then enqueuing the latter script with JQuery dependency in 3rd argument i.e array('jquery') that's what mostly people forget.

    wp_enqueue_script( 'lapetitefrog-mobile-menu', get_template_directory_uri() . '/js/mobile-menu.js', array('jquery'), '1.0', true );
    
    0 讨论(0)
  • 2020-12-31 02:57

    The error jQuery is not defined might also appear with jQuery code embedded in your template parts.

    This happens when jQuery is added to the footer of the page, while the embedded script tries to execute in the middle of the page.

    If this is the case, you need to load jQuery in the header with wp_enqueue_script(). So the last parameter needs to be false here:

    wp_enqueue_script( 'my-jquery', get_template_directory_uri() . '/js/jquery.js', array(), time(), false );
    

    Now the code executes in the right order and jQuery will be defined.

    Another solution would be to move the embedded script to a Javascript file that will also be added with wp_enqueue_script() to the footer of the page. This is up to you.

    0 讨论(0)
提交回复
热议问题