Search code examples
javascriptjqueryconflicting-libraries

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?


Solution

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