hguser hguser - 5 months ago 14
Javascript Question

How to get the absolute path of the current javascript file name

I have a javascript file named

main.js
.

Inside
main.js
I want to get the absolute path of this current file, something like:

http://server/app/main.js

http://server/app/script/main.js


What is the fastest way to get the absolute path?

Answer

You can investigate script collection at:

var scripts = document.getElementsByTagName("script");

For each element in the returned scripts array you can access its src attribute.

The currently executing include file will always be the last one in the scripts array. So you can access it at scripts[scripts.length-1].

Of course this will only work at time of initial code run and would not be useful for example within a function that is called after initial script is loaded, so if you need the value available later, you would need to save it to a variable.