How do I use @require and @resource?

in Script development
Subscribe to How do I use @require and @resource? 5 posts, 4 voices



khopesh Scriptwright

The documentation on this is extremely limited ... how do I use it? If I have to name my resources (which makes sense), how do I refer to those names? When is the @require code loaded? How do I keep it around after greasemonkey's sandbox is killed (tough question!)?

If you've got lots of detail to include here, please feel free to create a userscript.org guide.

 
Yansky Scriptwright

I duuno if this is the right way to do it, but using unsafeWindow seems to work:

// ==UserScript==
// @name          Hello jQuery
// @namespace     http://wiki.greasepot.net/examples
// @description   jQuery test script
// @include       *
// @require	  http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js
// ==/UserScript==

if(unsafeWindow && unsafeWindow.jQuery){
	$ = unsafeWindow.jQuery;
} 
$("a").click(function() {
	alert("Hello world!");
});

edit: actually scratch that. It doesn't seem to work properly.

 
VIPPER Scriptwright

// ==UserScript==
// @name          Test
// @namespace     test
// @description   testing require and resource
// @include       *
// @require       http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js
// @resource      image1 http://static.userscripts.org/images/userscripts.org.png?1225264897
// ==/UserScript==

$(document).ready(function() {
	$("a").click(function() {
		alert("Hello world!");
	});
});

newImage = document.createElement("IMG");
newImage.setAttribute("src", GM_getResourceURL("image1"));
document.body.appendChild(newImage);
@require is loaded on document.ready, I believe.
For @resource: GM_getResourceText and GM_getResourceURL

 
khopesh Scriptwright

But if I want to AJAXify the page or add buttons to it, I can't use @require for that. I'll try adding it as a @resource.

Isn't GM_getResourceURL redundant, since the resource was defined by its URL in the metadata? I suppose it prevents the need to enter it twice in a document, but I can't fathom using it without GM_getResourceText. Thanks for the pointers, I'll take a look at GM_getResourceText().

 
w35l3y Scriptwright

GM_getResourceURL is good for binary data, like images
GM_getResourceText is for plain text

GM requests @resource and @require at the first install, i mean, they won't be updated unless their keys change.
both are good for static data.

you need to use GM_xmlhttpRequest if you are trying to request dynamic data, like rss feed or whatever.

I'd like to know how keep them around too, that would be nice. especially @require