jQuery Greasemonkey Template & Netflix Queue Shuffler

jQuery is quickly becoming my weapon of choice to do DOM manipulation/enhancement. I'm still a huge Prototype fan for general code, but jQuery really does the DOM well.

So, when I set out to write a Greasemonkey script to randomize the order of the movies in my Netflix queue, I needed to find a way to include jQuery. The end result is fairly brief:

// ==UserScript==
// @name
// @namespace
// @description
// @include
// ==/UserScript==

* @param {Function} func the function you want to execute
* with jQuery. The only argument passed will be jQuery, so
* your function should look something like this:<pre>
* withJQuery( function($) {
* $(".foo .bar")...
* } );
* </pre>
function withJQuery(func) {
if(!unsafeWindow.jQuery) {
var s = document.createElement('script');
s.src = '';

s.addEventListener('load',function() {
// lots of people like to have their own $ function

} else {

// your code goes here, use withJQuery when you need it

The trick was figuring out that in a Greasemonkey script, you can't do element.oneventname = handler (you have to use addEventListener) and that once jQuery loaded, it would be in unsafeWindow, not window.

If you came here for the queue shuffle script, sorry to have bored you. I'll do another 'JavaScript for Java Devs' chapter soon.