Perhaps you don't have a recent enough version of Greasemonkey. It was version 0.8 that added @require
.
// @require https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js
If you don't have 0.8, then use the technique Joan Piedra describes for manually adding a script
element to the page.
Between version 0.8 and 0.9, @require
is only processed when the script is first installed. If you change the list of required scripts, you need to uninstall your script and reinstall it; Greasemonkey downloads the required script once at installation and uses a cached copy thereafter.
As of 0.9, Greasemonkey behavior has changed (to address a tangentially related issue) so that it now loads the required scripts after every edit; reinstalling the script is no longer necessary.
If you want to use jQuery on a site where it is already included, this is the way to go (inspired by BrunoLM):
var $ = unsafeWindow.jQuery;
I know this wasn't the original intent of the question, but it is increasingly becoming a common case and you didn't explicitly exclude this case. ;)
There's absolutely nothing wrong with including the entirety of jQuery within your Greasemonkey script. Just take the source, and place it at the top of your user script. No need to make a script tag, since you're already executing JavaScript!
The user only downloads the script once anyways, so size of script is not a big concern. In addition, if you ever want your Greasemonkey script to work in non-GM environments (such as Opera's GM-esque user scripts, or Greasekit on Safari), it'll help not to use GM-unique constructs such as @require.
Rob's solution is the right one--use @require
with the jQuery library and be sure to reinstall your script so the directive gets processed.
One thing I think is worth adding is that you can use jQuery normally once you have included it in your script, except for AJAX methods. By default jQuery looks for XMLHttpRequest, which doesn't exist in the Greasemonkey context. I wrote about a workaround where you create a wrapper for GM_xmlhttpRequest (the Greasemonkey version of XHR) and use jQuery's ajaxSetup()
to specify your wrapped version as the default. Once you do this, you can use $.get
and $.post
as usual.
You may also have problems with jQuery's $.getJSON
because it loads JSONP using <script>
tags. This leads to errors because jQuery defines the callback function in the scope of the Greasemonkey window, and the loaded scripts looks for the callback in the scope of the main window. Your best bet is to use $.get
instead and parse the result with JSON.parse()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With