开发者

JS embedded on other sites - how can I use jQuery without screwing up other jQuery installations?

开发者 https://www.devze.com 2023-01-21 16:03 出处:网络
I\'m working on some JavaScript that will be embedded on other websites (think like Google Analytics or AdSense). There is some hardcore JS being done -- AJAX requests, animations, JSON(P).

I'm working on some JavaScript that will be embedded on other websites (think like Google Analytics or AdSense). There is some hardcore JS being done -- AJAX requests, animations, JSON(P).

I've written the prototype using jQuery, and really want to keep using it, but this might cause a problem when embedded on the other sites if they also have jQuery installed -- probably even a different version.

Is there a nice way around this? The best开发者_JS百科 solution I've got so far is to simply replace all occurrences of jQuery with kQuery, and $ with $kQuery, so there is no naming conflict. Any suggestions? How can I be as compatible as possible with their existing JavaScript?


There is a noConflict mode for jQuery; that's what you need. jQuery saves the original values of window.jQuery and window.$ as a local copy before it overwrites them.

So, a solution is:

var kQuery = $kQuery = $.noConflict( true );

Which replaces window.jQuery and window.$ with the original values and returns a reference to jQuery itself


And if you don't want to change your code at all, just wrap it in:

(function( $ ){
   // Your code with $
})( $.noConflict( true ) );


 this might cause a problem when embedded on the other sites if they also have jQuery installed -- probably even a different version

I don't think this is true. I've had no problems switching between at least 3 different versions of jQuery, it is backwards compatible

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号