10

Possible Duplicate:
What is my script src URL?

I have situation:

<script 
  type="text/javascript" 
  src="http://server/some.js">
</script>

In file some.js I need to know full path of same file some.js, eq. "http://server/some.js". How can I do this?

I can't change HTML code (clients are including JS file).

1

3 Answers 3

9

try that one

sc = document.getElementsByTagName("script");

for(idx = 0; idx < sc.length; idx++)
{
  s = sc.item(idx);

  if(s.src && s.src.match(/some\.js$/))
  { return s.src; }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Tomasz, am I missing something or where do you initialise sc? Also, IMO the whole thing is cleaner if you add the var keyword before idx = 0 and s. Nice piece of code, otherwise.
Tom Bartel - you were right fixed and thx for the tip on that
without var idx=0 in the for loop you will introduce a global idx variable (unless you previously defined idx with var)
9

The simplest way is just to look for the last script to be added to the document:

var scripts= document.getElementsByTagName('script');
var mysrc= scripts[scripts.length-1].src;

This has to be done in the main body of the script, not in code called later. Preferably do it at the start of the script and remember the variable so it can be used in later function calls if necessary, and so it's not affected by code later in the script inserting any new <script> nodes into the document.

1 Comment

Does this with with the async attribute too?
0

Not sure it works in all browsers, by try this:

function getScriptFileName() {
  return (new Error).fileName;
}

2 Comments

Sadly no, the Error object is unstandardised and fileName only seems to exist in Mozilla.
Seems does not work in Safari.