This is a great method to get jQuery working with your Greasemonkey scripts. This method was inspired by Joan Piedra’s jQuery & Greasemonkey snippet:
GM_jQuery.src = 'http://jqueryjs.googlecode.com/files/jquery-1.2.6.pack.js';
GM_jQuery.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(GM_jQuery);
// Wait until jQuery has loaded
function GM_wait() {
if( typeof unsafeWindow.jQuery == 'undefined' ) {
window.setTimeout(GM_wait,100);
} else {
$ = unsafeWindow.jQuery;
GM_ready();
}
}
GM_wait();
// Once document and jQuery are loaded
function GM_ready() {
//
// [Your Greasemonkey code here]
//
}
You can avoid occassional page load lags by changing the link to jQuery to one on your own server. Note that you won’t need to use this code if jQuery is already being used on the corresponding website.
Surely in the year or more since the first betas of v0.8 came out it’s no longer necessary to do this? You can instead just specify any files you want to get included in the metadata e.g.
// @require http://jqueryjs.googlecode.com/files/jquery-1.3.2.js
which will execute that file just before your script runs.
There’s a bit of a big hole in GM though as if you use the “New User Script” option in menu then this doesn’t work at all – GM only imports anything referenced by @require the first time you install the script, and the “New User Script” option creates and installs a default user script for you, so even if you add the @require it fails.
It’s not much harder to create a .user.js file manually and browse to it… took me ages to find out I needed to though!
Just wrote my first webmonkey script and used jquery, WOOT! Thanks guys..
btw, the // @require thing worked just as James said it would.. one line, no fuss and no muss hehe :)
Agreed. Thanks, James, for bringing up the new @require method :)
Hi. This is very nice, thanks.
But is there a way to avoid the download of jquery everytime? I tried a local URL (eg /home/otto/jquery.js) and it doesn’t work.
That “lag” is a bit boring and requires internet access.
Thank you.
Otto – previously mentioned by James was the “@require” metadata that you can add to the top of the file. I would highly suggest viewing this article regarding how to create your own .user.js file and then installing it with greasemonkey, http://greasemonkey.mozdev.org/authoring.html
Hope that helps!