The Pug Automatic

jQuery in GreaseKit

Written July 21, 2009. Tagged JavaScript, jQuery, Userscripts, Greasemonkey, GreaseKit.

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:

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.