Suppose I have a script tag somewhere in my page as follows:
<script type="text/javascript" src="myscripts.js"></script>
I would want to get the exact uri of the js page (something like
http://mysite.com/myscripts.js). Or at least get the name of the js
file (myscripts.js). Is this possible?
Yes you can get the URI, but there are some problems with differences
between IE and most other browsers.
There are several questions, though. First, where are you doing it
from? Are you trying to find the URI from within myscripts.js, or
from within another script? Second, if it's the latter, how do you
identify among the possibly numerous SCRIPT elements the one you
want? Can you give it an id?
In general, though,
var scripts = document.getElementsByTagName("SCRIPT");
will give you a list of the script tags. Then you have to find the
correct one. If you are doing this code within the linked script, you
*might* be able to use scripts[scripts.length - 1] to refer to the
current script element; I haven't tested this widely, though. I
believe that although the scripts can be downloaded in any order, they
are supposed to be evaluated in document order.
Once you have your script element, you can check it's "src"
attribute. Here's where IE often differs from the other browsers; it
might well return "myscript.js", while the others will likely return
"
http://mysite.com/myscript.js". You will have to resolve this by
combining the short form with the document.location.href or -- if a
BASE element is present -- the href of the BASE element. This is not
trivial to do, but it's not too hard either. I'm sure there are
examples of this to be found on the Web.
Good luck,
-- Scott