views:

227

answers:

1

Hi. What is the best strategy to supply a necessary new version of jQuery (1.4.2) in a userscript, which modifies a page that already has an older version of jQuery (1.3.1)?

Preferably the original page continues to use '$' sign while in my script it uses an alias assigned by jquery.noConflict().

According to the answer to this question, any extra version one wishes to load should be placed above the original script tag. This is where I get a little confused, since I'm under the impression GreaseMonkey executes the script after page loads?

EDIT: One thought is in the userscript, append a script tag for jQuery 1.4.2, set alias, then append a script tag for 1.3.1 again so as to not break the original page's code, which uses 1.3.1 functions.

var code142 = function() {
    gj = jQuery.noConflict(true);
    alert("142...");
    alert(gj); // check if the dollar (jquery) function works
    alert(gj().jquery); // check jQuery version
}

var script = document.createElement("script");
script.src = 'http://code.jquery.com/jquery-1.4.2.min.js'
document.documentElement.appendChild(script);


// assign jquery object alias and run code that uses 1.4.2 there
var script = document.createElement("script");
script.textContent = '(' + code142.toString() + ')();';
document.documentElement.appendChild(script);

/* The following is perhaps redundant, see EDIT 2 for more info

// add jquery 1.3.1 (again)
var script = document.createElement("script");
script.src = 'http://code.jquery.com/jquery-1.3.1.min.js'
document.documentElement.appendChild(script);

*/

But this will require loading the jQuery library 3 times per page. Is there any better way?

EDIT 2: It seems the original page could still use its 1.3.1 copy, despite that the GM script has supplied a 1.4.2 copy, they can co-exist just as long as I use the new alias (gj) to refer to the 1.4.2 jQuery object inside code142().

If nothing else comes up then this would be my solution. I hope it's useful to other folks who may run into this problem.

A: 

I believe this is what you're looking for.

As long as you're doing nothing complicated and the newest version isn't required, follow the pattern in the link for including it.

It checks if jQuery is loaded (typeof unsafeWindow.jQuery == 'undefined') before including again. The "simple" part just means that will what you're doing work in both 1.3 and 1.4, possibly 1.2.6? If that's the case it doesn't matter which version you load, as long as it's loaded. (Unless it's a very old site, then check that the functions you're using so way back in jQuery core, but this is much less likely)

Nick Craver
Hi. The newest version is required in this case, since the older version on the original page does not support some of the functionality I want to use for my userscript.
Dan7