Search code examples
javascriptjquerygreasemonkey

How do I include a remote javascript file in a Greasemonkey script?


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.


Solution

  • 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.