How do I get the absolute or site-relative path for an included javascript file.
I know this can be done in PHP, (__file__
, I think). Even for an included page, one can check the path (to the included file). Is there any way to have this self awareness in Javascript?
I know I can can get the page URL, but need to get the JS URL.
Eg. Javascript needs to modify the src of an image on the page. I know where the image is relative to the JavaScript file. I don't know where the Javascript is relative to the page.
<body>
<img id="img0" src="">
<script src="js/imgMaker/myscript.js"></script>
</body>
function fixPath(){
$$("#img0")[0].set('src','js/imgMaker/images/main.jpg');
}
Please do not tell me to restructure my function - the example is simplified to explain the need. In the actual case, a Mootools class is being distributed and people can put it into whatever folder they want.
I would just read the src of the script element, but the class can be part of any number of javascript files, so I can't know what the element looks like.
The path to the JS is irrelevant; links in the HTML file are always relative to the HTML file, even if you modify them from external JS.
[EDIT] If you need to build a path relative to the current web page, you can find its path in
document.location.pathname
. This path is relative to the web root but you should be able to find a known subpath and then work from there.For example, for this page, it
pathname
would be/posts/1858724
. You can look forposts
and then build a relative path from there (for exampleposts/../images/smiley.png
)JavaScript (not JScript) has no concept of file names. It was developed for Netscape back in the days. Therefore there is no
__file__
feature or anything similar.The closest you can come are these two possibilities:
What you already mentioned: Harvest all
src
attributes of all JS files and try to figure out which one is the right.Make it a necessary option, that the path to the images must be set in the embedding HTML file. If not set, use a reasonable and well-documented default:
if you have folders:
Then images would be an absolute path of /images/whatever.jpg and scripts would be an absolute path of /scripts/js.js
I know this question was asked awhile back but I have a similar situation to Sam's.
In my case, I have two reasons for the situation:
Most of the references point to the same src locations for the scripts, but some do not. For instance, those at a different level of the tree would require a different path.
I addressed it by assigning an id to the index page's script tag. For example, the head might include...
My JavaScript is then able to read the path...
Based on http://ejohn.org/blog/file-in-javascript/
Then later
I'm using the following method to get the base URL and using it for loading the other prorotypes, maybe this is what you need. Lets say current script name is 'clone.js'.
Var baseURL should contain what you need.