如何获取当前javascript文件名的绝对路径

如何获取当前javascript文件名的绝对路径

问题描述:

我有一个名为 main.js 的javascript文件。

I have a javascript file named main.js.

内部 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?

您可以在以下位置调查脚本集合:

You can investigate script collection at:

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

对于返回的脚本数组中的每个元素您可以访问其 src 属性。

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

当前正在执行的包含文件将始终是脚本数组。所以你可以在 scripts [scripts.length-1] 中访问它。

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.