jQuery & Greasemonkey

How to play nicely with jQuery and Greasemonkey

jQuery & Greasemonkey


Overview

This is a simple snippet that helps us load the jQuery power into our userscripts with Greasemonkey 0.7 or lower, newer versions may use @require.


Updates

2010-04-24:
The userscript checks if jQuery is already loaded in the page and uses it, otherwise loads it from Google's CDN. It's also using jQuery.noConflict(true).

Thanks to everyone who sent me emails about this over this and last year.


Code

JS call

var $;

// Add jQuery
    (function(){
        if (typeof unsafeWindow.jQuery == 'undefined') {
            var GM_Head = document.getElementsByTagName('head')[0] || document.documentElement,
                GM_JQ = document.createElement('script');
    
            GM_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';
            GM_JQ.type = 'text/javascript';
            GM_JQ.async = true;
    
            GM_Head.insertBefore(GM_JQ, GM_Head.firstChild);
        }
        GM_wait();
    })();

// Check if jQuery's loaded
    function GM_wait() {
        if (typeof unsafeWindow.jQuery == 'undefined') {
            window.setTimeout(GM_wait, 100);
        } else {
            $ = unsafeWindow.jQuery.noConflict(true);
            letsJQuery();
        }
    }

// All your GM code must be inside this function
    function letsJQuery() {
        alert($); // check if the dollar (jquery) function works
        alert($().jquery); // check jQuery version
    }

Download


MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so.