Amy B
Amy B

Reputation: 17977

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

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?

Upvotes: 1

Views: 73

Answers (2)

Harmen
Harmen

Reputation: 22438

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 ) );

Upvotes: 3

NimChimpsky
NimChimpsky

Reputation: 47280

 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

Upvotes: 0

Related Questions