views:

17

answers:

2

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?

A: 
 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

NimChimpsky
I might be using new features (e.g. JSONP support) that aren't available in previous versions.
Coronatus
+3  A: 

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