5

How can I find out the URL of the JS file that was called?

Let's say the JS file (which is part of a library) and the HTML file (which is the application) are on a different server. To find out the URL of the HTML file is easy. But how can I find out the server name and path of the JS files' server within the JS file itself? (Edit: There is a loader which invokes other JS files of thsi library in the same directory structure)

Preferably a JQuery or pure JS solution.

Edit:

After I learned from your answers and comments I decided it would be cleaner to actually move the loader code to the first server, where also the html lives, which avoids the problem.

4
  • What do you need it for? Commented Nov 23, 2010 at 1:17
  • @Josh: to load more js files from the same server. Commented Nov 23, 2010 at 1:18
  • Couldn't you use php to dynamically create a js file and include any js code you want? Commented Nov 23, 2010 at 1:21
  • why don't do in the backend instead from javascript Commented Nov 23, 2010 at 1:26

2 Answers 2

4

In JQuery you could do:

$('script').each(function(i, e) {
    alert($(e).attr('src'));
});
Sign up to request clarification or add additional context in comments.

2 Comments

Would you then use $.append to add a script to the document? I'm not sure it would load it then.
@Fred - To load an async JS file you should use getScript(), just to make sure your callback is called after the JS file is completely loaded.
2

You can iterate through the script tags and check the SRC, I suppose...

var els = document.getElementsByTagName("script");
var str = "";

for(var i = 0; i < els.length; i++) {
  var src = els[i].src;
  if(src.length > 0)
    str += src + "\n";
}

alert(str);

Paste the following into your browser bar to see the URLs of the scripts on this page...

javascript:var els = document.getElementsByTagName("script"); var str = ""; for(var i = 0; i < els.length; i++) { var src = els[i].src; if(src.length > 0) { str += src + "\n";}}alert(str);

Note: IE appears to only iterate through <script> elements within the <body> tag.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.