When someone wants to write a bit more complex javascript with Greasemonkey, the plain getElementsBy functions may not be enough: enter jQuery. But how to include jQuery, without messing up the original document, eg. without causing a leak to the unsafeWindow? Most people include it the old way (using header script inclusion), which is not that nice; here’s what I do (though probably nothing new under the sun):
(function(){
GM_xmlhttpRequest({
method: "GET",
url: "http://jqueryjs.googlecode.com/files/jquery-1.2.6.pack.js",
onload: run
});
function run(details) {
if (details.status != 200) {
GM_log("no jQuery found!");
return;
}
eval(details.responseText);
var $ = jQuery;
//do something useful here....
}
})();
First we bootstrap jQuery using the GM_xmlhttpRequest builtin function (cross-domain ajax from GM) then we evaluate the whole stuff in our little sandbox. Hope someone finds this useful.
Edit: as Tibor noted bellow in the comments there’s a new require tag in Greasemonkey 0.8+, that can be used for the same purpose. Unfortunately no matter how hard I tried it with Firefox 3.0.1 and GM 0.8.2008x this did not work, or at least the provided example did nothing for me.