29

I'm trying to write a Greasemonkey script, and would like to use the jQuery library to do so, but I'm not quite sure how I would include jQuery from a web address to get rolling.

How would I include jQuery (from Google's web server) into the greasemonkey script so that I can just go:

$(document).ready(function(){
  // Greasemonkey stuff here
});

I'd prefer to get it from this source:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>

Update: Thanks for the help, the answers were very informative. I did, however, utilize my GoogleFu a little more and came across this solution: http://joanpiedra.com/jquery/greasemonkey/

Works like a charm.. just update the source to google's hosted version of jQuery to complete.

Cheekysoft
  • 35,194
  • 20
  • 73
  • 86
tester
  • 22,441
  • 25
  • 88
  • 128

4 Answers4

52

The recommended way in recent versions of greasemonkey is to use the @require comment tag.

E.g.

// ==UserScript==
// @name          Hello jQuery
// @namespace     http://www.example.com/
// @description   jQuery test script
// @include       *
// @require       http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
// ==/UserScript==

However... be aware that jQuery 1.4.1 and 1.4.2 are incompatible with this method

Thanks Paul Tarjan, for pointing this out. See jQuery forum thread.

Also be aware of these @require semantics

At the time that the user script is installed, Greasemonkey will download and keep a locally cached copy of the remote file that can be read almost instantly. The cached copy is kept in the same folder as your installed user-script. The remote file is not monitored for changes.

Please be aware that, at the time of writing this answer, this @require tag is only read at install-time. If you edit an existing user script to add this tag, it will be ignored. You need to uninstall and re-install your user script to pick up the change.

Cheekysoft
  • 35,194
  • 20
  • 73
  • 86
  • Wow, that is an extremely simple solution. That's awesome it caches too! Thank you. – tester Apr 25 '09 at 03:45
  • awesome, complete and great answer. – Dan Rosenstark Dec 10 '09 at 21:08
  • 3
    Careful, this doesn't work for 1.4.1 or 1.4.2 : http://forum.jquery.com/topic/importing-jquery-1-4-1-into-greasemonkey-scripts-generates-an-error – Paul Tarjan Apr 12 '10 at 06:42
  • The cache feature is great and I always use it on my gs scripts. I use http://jqueryjs.googlecode.com/files/jquery-1.2.6.pack.js as its small/packed and most of the time it has what I need. – fedmich Aug 10 '10 at 13:14
  • 1
    @fdrv Try putting a query string on the URL, e.g. add today's date. `http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?2018-10-08` – Lee Kowalkowski Oct 08 '18 at 08:56
  • This doesn't work if you're trying to use jsconsole.com to log your userscript's console output, at least with Tampermonkey. You get an error that "couldn't load @require from URL". – John Smith Jul 28 '19 at 00:07
12

From here:

// ==UserScript== 
// @name           jQueryTest 
// @namespace      http://www.example.com/
// @include        * 
// ==/UserScript== 

// Add jQuery 
var GM_JQ = document.createElement('script'); 
GM_JQ.src = 'http://jquery.com/src/jquery-latest.js';
GM_JQ.type = 'text/javascript'; 
document.getElementsByTagName('head')[0].appendChild(GM_JQ); 

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

// All your GM code must be inside this function 
function letsJQuery() { 

    alert($); // check if the dollar (jquery) function works 
    // the next call fails 
    $("<div id='example' class='flora' title='This is my title'>I'm in 
a dialog!</div>").dialog({ 
            buttons: { 
                "Ok": function() { 
                    alert("Ok"); 
                }, 
                "Cancel": function() { 
                    $(this).dialog("close"); 
                } 
            } 
        }); 
} 

It works perfectly, but you may want to limit the sites it runs on or host the jQuery js file on your own site so as not to steal their bandwidth.

Chris Doggett
  • 19,959
  • 4
  • 61
  • 86
  • haha that's rad that you just posted that too. I just found that link and replaced GM_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js'; Thank you for contributing!! – tester Apr 23 '09 at 01:35
  • This is not necessary for recent versions of greasemonkey and you can use the @require tag instead. – Cheekysoft Dec 11 '09 at 09:57
  • 1
    A benefit of using this method is that it should work on Chrome, where using @require will not. – Mike Buckbee Apr 03 '11 at 05:19
  • it doesnt work if i need load script from http for https – fdrv Mar 16 '16 at 18:29
6

You could try dynamically creating a script element:

var script = document.createElement("script");
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
document.getElementsByTagName("head")[0].appendChild(script);

You may need to delay for a bit while the script loads (setTimeout?)

Emmett
  • 14,035
  • 12
  • 56
  • 81
2

Based on Chris's answer, I adjust to my own needs like following.

// ==UserScript==
// @description require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.jss
// @name         Baidu Mask
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://www.ibm.com/developerworks/cn/opensource/os-cn-greasemonkey/index.html
// @match        *://www.baidu.com/*
// @match        *://baike.baidu.com/*
// @match        *://zhidao.baidu.com/*
// @match        *://www.weather.com.cn/*
// @grant        none
// ==/UserScript==

(function () {
    'use strict';

    // Your code here...

    var $j;

    function GM_wait() {
        if (typeof jQuery === 'undefined') {
            window.setTimeout(GM_wait, 100);
        }
        else {
            $j = jQuery.noConflict();
            doJob();
        }
    }

    function loadJquery() {
        // Check if jQuery's loaded

        if (typeof jQuery === 'undefined') {
            // Add jQuery
            var GM_JQ = document.createElement('script');
            GM_JQ.src = 'https://code.jquery.com/jquery-1.12.4.min.js';
            GM_JQ.type = 'text/javascript';
            GM_JQ.id = 'jquery-lyz';
            document.getElementsByTagName('head')[0].appendChild(GM_JQ);
            GM_wait();
        } else {
            doJob();
        }
    }

    loadJquery();


    function doJob() {
        if (typeof $j === 'undefined') {
            $j = $;
        }

        var url_arr = [
            {'name': "baidu", 'value': "www.baidu.com"},
            {'name': "baike", 'value': "baike.baidu.com"},
            {'name': "zhidao", 'value': "zhidao.baidu.com"},
            {'name': "weather", 'value': "http://www.weather.com.cn"},
        ];
        var url = location.href;
        var siteObj = {};
        $j(url_arr).each(function (i, item) {
            if (url.indexOf(item.value) > -1) {
                siteObj = item;
                return false;
            }
        });

        var delay_arr = [];
        var timerCount = 1;

        function hideTimer() {
            timerCount++;
            if (timerCount > 20) {
                return;
            }
            delay_arr = $j.grep(delay_arr, function (_selector, i) {
                var $ele = $j(_selector);
                var visible = $ele.is(':visible');
                console.log($ele, visible);
                if (visible) {
                    $ele.hide();
                    return false;
                }


                return true; // keep the element in the array
            });
            if (delay_arr.length > 0) {
                setTimeout(hideTimer, 500);
            }
        }

        setTimeout(hideTimer, 500);
        var $frms;
        switch (siteObj.name) {
            case 'baidu':
                $j('#content_right').hide();
                break;
            case 'baike':
                $j('.topA, .lemmaWgt-promotion-slide, .union-content, .right-ad, .lemmaWgt-promotion-vbaike, .nav-menu').hide();
                delay_arr.push('#side_box_unionAd');
                break;
            case 'zhidao':
                $j('.widget-new-graphic, #union-asplu, .jump-top-box').hide();
                delay_arr.push('.wgt-daily');
                delay_arr.push('.shop-entrance');
                delay_arr.push('.cms-slide');
                delay_arr.push('.nav-menu');
                $frms = $j('iframe');
                $frms.hide();
                break;
            case 'weather':
                $j('.right, .hdImgs, .tq_zx, #di_tan, #zu_dui').hide();
                //delay_arr.push('.wgt-daily');
                $frms = $j('iframe');
                $frms.hide();
                break;
        }
    }

})();

My script need to work on different sites, while some has jquery included and some not, so I have to test out. The "require" way not work here.

Leo Lee
  • 468
  • 5
  • 16