开发者

How can I get URL of JS file in same JS file? [duplicate]

This question already has answers here: Closed 13 years ago.

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).


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; }
}


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.


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜