Tower
Tower

Reputation: 102795

Retrieving JavaScript source file location?

If I load a JavaScript source file like so:

<!DOCTYPE html>
<html>
    <head>
        <script src="src/file.js"></source>
    </head>
    <body>
    </body>
</html>

My question is that how could file.js know that the relative path to its location is src/? I need this information for building up a URL from the source file that depends on the URL it was loaded from.

Upvotes: 2

Views: 4569

Answers (2)

jerone
jerone

Reputation: 16871

If you use getAttribute you'll get the written src. If you use the .src attribute, you'll get the src with current location.

http://jsbin.com/igixi5/5/

Upvotes: 0

RobertO
RobertO

Reputation: 2663

<script src="src/file.js" id="script0"></script>

In file.js:

var path = document.getElementById ( "script0" ).getAttribute ( "src" );

Upvotes: 2

Related Questions