Bullet proof way to avoid jquery conflicts on word

2019-03-27 19:30发布

I have been developing wordpress plugins for a while now and i always seem to get the following issues with all my plugins Jquery conflicts issues.

I have tried so many different ways to avoid these but i always get users contacting me saying when they have installed one off my plugins it has stopped another plugin from working aahhhhh.

I really want to get this sorted because i understand how frustrating this can be for people.

I always set and option or include wordpresses jquery, below is just an example not working code.

add_action( 'init', array( $this, 'include_jquery' ) );

function include_jquery(){

                   wp_deregister_script('jquery');
                   wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"), false, '1.7.1');
                   wp_enqueue_script('jquery');

            }

Ok so after issues with this i now have a select option in the plugin admin to toggle yes or no to include jquery or not i know it is automatically installed but some users remove this, this works for some people but not all.

if you include the wordpress jquery i know you have to run your jquery with the following.

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

jQuery instead of the dollar sign $

i understand and have used jquery no conflict and tried and tested some if not all off these http://api.jquery.com/jQuery.noConflict/

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

This as with the others works for some but not all users with conflicts arising still with certain users.

I am hoping that from this post some of us wordpress plugin developers could help out and post a bullet proof way to use wordpress and jquery within our plugins without getting conflict issues.

Thanks

2条回答
别忘想泡老子
2楼-- · 2019-03-27 19:57

Read these parts of the codex :

You should use wp_enqueue_scripts hook instead of init.

And you should use jQuery.noConflict(); instead of $.noConflict();.

查看更多
叛逆
3楼-- · 2019-03-27 20:01

Doesn't it work with a closure?

(function($){
    // your plugin code
})(jQuery);
查看更多
登录 后发表回答