tags:

views:

37

answers:

2

We are writing a SaaS like solution that requires our customers to SCRIPT SRC some javascript code we are building (think Google Analytics scenario). We would like to use JQuery. However, since our customers might already have conflicting JQuery versions or other conflicting frameworks (prototype.js for one) we cannot tell them to source jquery.js.

We were thinking of coping the jquery source as to create a 'private' jquery instance and simple search/replace the JQuery and $ functions with myJQuery and $J

Is there any reason for this not to work? has anyone tried something like this? What can we do about plugins?

+2  A: 

You should be able to achieve this using jQuery.noConflict()

This though doesn't fix the plugin problem:

Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If we need to use another JavaScript library alongside jQuery, we can return control of $ back to the other library with a call to $.noConflict():

This technique is especially effective in conjunction with the .ready() method's ability to alias the jQuery object, as within callback passed to .ready() we can use $ if we wish without fear of conflicts later:

If necessary, we can free up the jQuery name as well by passing true as an argument to the method. This is rarely necessary, and if we must do this (for example, if we need to use multiple versions of the jQuery library on the same page), we need to consider that most plug-ins rely on the presence of the jQuery variable and may not operate correctly in this situation.

Stuart Dunkeld
thanks, I should really have RTFMed this.
Nir Levy
+2  A: 

You could do something like this:

// << include your own jQuery version >> 

alert("jQuery version: " + jQuery().jquery);  // 1.4.2 -- or whatever you included

ourJQ = jQuery.noConflict(true);

alert("jQuery version: " + jQuery().jquery); // 1.3.2 -- or whatever was included before

If you are including plugins or anything, just wrap it all in an anonymous function to create a closure:

(function ($) {
    // in here, $ is your jQuery version
    alert($().jquery); // "1.4.2"
})(ourJQ);

// out here, $ is the previously included version
alert($().jquery) // "1.3.2"
nickf
+1 here. Thanks for the detailed explanation. Wish I could accept more then one answer..
Nir Levy