1

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 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?

Amy B
  • 17,874
  • 12
  • 64
  • 83

2 Answers2

3

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 ) );
Harmen
  • 22,092
  • 4
  • 54
  • 76
0
 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

Community
  • 1
  • 1
NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
  • I might be using new features (e.g. JSONP support) that aren't available in previous versions. – Amy B Oct 25 '10 at 12:36