admin管理员组

文章数量:1435805

How register from my plugin level correct jquery?

If i run this :

 function insertJQuery() {

               wp_deregister_script('jquery');
               wp_enqueue_script('jquery', '.1.1/jquery.min.js', array(), null, true);

     }

  add_action('wp_enqueue_scripts', 'insertJQuery');

And this work, but if i run this:

    function theme_scripts() {
              wp_enqueue_script('jquery');
    }

    add_action('wp_enqueue_scripts', 'theme_scripts');

Then scripts in site not work. I read to use the jquery version installed in WP. How do you finally use it correctly to be safe?

How register from my plugin level correct jquery?

If i run this :

 function insertJQuery() {

               wp_deregister_script('jquery');
               wp_enqueue_script('jquery', 'https://ajax.googleapis/ajax/libs/jquery/3.1.1/jquery.min.js', array(), null, true);

     }

  add_action('wp_enqueue_scripts', 'insertJQuery');

And this work, but if i run this:

    function theme_scripts() {
              wp_enqueue_script('jquery');
    }

    add_action('wp_enqueue_scripts', 'theme_scripts');

Then scripts in site not work. I read to use the jquery version installed in WP. How do you finally use it correctly to be safe?

Share Improve this question edited Mar 31, 2019 at 17:54 Krzysiek Dróżdż 25.6k9 gold badges53 silver badges74 bronze badges asked Mar 31, 2019 at 17:48 JaronJaron 458 bronze badges 1
  • Possible duplicate of How to include jQuery and JavaScript files correctly? – Willi Commented Apr 1, 2019 at 2:51
Add a comment  | 

1 Answer 1

Reset to default 2

You should use the built-in version of jQuery for compatibility reasons.

All you need to do is to enqueue it:

function theme_scripts() {
    wp_enqueue_script('jquery');
}
add_action('wp_enqueue_scripts', 'theme_scripts');

Or just add it as a dependency for your script:

function theme_scripts() {
    wp_enqueue_script( 'my-script', <PATH>, array('jquery'), ... );
}
add_action('wp_enqueue_scripts', 'theme_scripts');

But then... you have to remember, that jQuery is run in no-conflict mode, so in your scripts you have to access it by jQuery and not by $. So your script should look like so:

jQuery(function ($) {
    // here you can use $ sign to get jQuery, because of the param of function

    $('a').click(...); // so this will work OK
});

// but here you can't and you have to use jQuery
jQuery('a').click(...); // this will work also

$('a').click(...); // but this won't, because there is no $ accessible here

本文标签: wp enqueue scriptHow register library to use jquery correct