To expand a little bit on the answer from Doug, I think this can be done in way that seems like much less of a hack. I have frequently used a similar pattern to pass information such as static resource urls, object describe information, or anything else available in a visualforce global variable to a javascript file.
To make this more robust, you will want to add these items to a namespace object. This prevents conflicts with someone else re-defining the variable globalStaticResourcePath
. This would look like:
Visualforce
<script>
// Declare your namespace with an anonymous function. Replace "myNs" in
// this code with whatever your namespace is. If you don't have one
// you can just make one up. Just don't use anything Salesforce already
// uses like "sfdc", "sfone", "force", etc.
(function(myNs, undefined) {
// Declare your custom $Resource object only if it is not already
// declared.
myNs.$Resource = myNs.$Resource || {};
// Add any resources you want to the object
myNs.$Resource.MyResource = '{!URLFOR($Resource.MyResource)}';
myNs.$Resource.OtherResource = '{!URLFOR($Resource.OtherResource)}';
//OPTIONAL: Add a helper function for getting resource urls
myNs.getResourceUrl = function(resourceName, filePath) {
var baseResourceUrl = myNs.$Resource[resourceName];
// Throw an error if you get a resource that does not exist
if(!baseResourceUrl) {
throw 'The static resource ' + resourceName + ' does not exist or has not been added to the $Resource map.';
}
var url = baseResourceUrl;
// If we have a file path, append it.
if(filePath) {
url = url + filePath;
}
// Return the resource url
return url;
};
}(window.myNs = window.myNs || {}));
</script>
Javascript
// Use your function or you could directly reference myNs.$Resource
var myImageUrl = myNs.getResourceUrl('MyResource', '/img/file.png');
var myResourceUrl = myNs.getResourceUrl('MyResource');
var otherResourceUrl = myNs.$Resource.OtherResource;
This can be made even more modular by placing the visualforce code inside a component that can be included on any page where you or someone else on your team needs to access resources from javascript.
-D.S.
icon: {!URLFOR($Resource.MyResource,'img/iconoTP.gif')},