Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Hey all, I've been trying to throw together a generic function that retrieves the absolute URL of an executing JavaScript file on a web page:

http://gist.github.com/433486

Basically you get to call something like this:

getScriptName(function(url) {
    console.log(url);
    // http://www.example.com/myExternalJsFile.js
});

inside an external JavaScript file on a page and can then do something with it (like find the <script> tag that loaded it for example).

It works great in almost all the browsers I've tested (Firefox, Chrome, Safari, Opera v10 at least, and IE 8).

It seems to fail, however, in IE 6 and 7. The callback function gets executed, but the retrieved name is the URL to the main HTML page, not the JavaScript file. Continuing with the example, getScriptName invokes the callback with the parameter: http://www.example.com/index.html

So all I'm really asking is if there's some other way of getting the URL of the current JavaScript file (which could be IE 6 and 7 specific hackery)? Thanks in advance!

EDIT: Also, this won't work in every case, so please don't recommend it:

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

I'd like it to work in the case of dynamically created script tags (possibly not placed last in the page), aka lazy-loading.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
380 views
Welcome To Ask or Share your Answers For Others

1 Answer

A lot of this depends on what you have access to. If, as it appears, you are trying to do this entirely within the JS code, I do not believe that you are able to do it, for some of the reasons shown above. You could get 90% of the way maybe, but not be definitive.

If you are working in a dotnet environment ( which is the only one I know ), I would suggest the use of a module that would intercept all JS requests and add into them the request location, or something of that nature.

I think you need to address this from the server side, not the client side. I do not think you will have a definitive answer form the client side. I think you will also struggle to get an answer from the server side, but you might be more successfull.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...