jQuery in GreaseKit

Written . Tagged GreaseKit, Greasemonkey, JavaScript, Userscripts, jQuery.

When writing userscripts, I almost always want to include the jQuery lib.

Since version 0.8.0 of Greasemonkey, you can use @require as described e.g. here. But if you use other userscript engines like GreaseKit for Safari/WebKit (works fine in Safari 4, by the way), you can’t use @require.

Rather than polling, you can do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function jQueryIsReady($) {

  $("#foo").text("bar");

}


// -----------------------------------------------------------------
// Greasemonkey/GreaseKit compatibility
// -----------------------------------------------------------------

if (typeof(unsafeWindow) === 'undefined') {
 unsafeWindow = window;
}

// -----------------------------------------------------------------
// jQuery
// -----------------------------------------------------------------

var script = document.createElement('script');
script.src = 'http://jquery.com/src/jquery-latest.js';
script.type = 'text/javascript';
script.addEventListener("load", function() {
  unsafeWindow.jQuery.noConflict();
  jQueryIsReady(unsafeWindow.jQuery);
}, false);
document.getElementsByTagName('head')[0].appendChild(script);

See it in the context of a real userscript.

Many thanks to Johan Sundström who did most of the work figuring this out.