如何获取当前javascript文件名的绝对路径 [英] How to get the absolute path of the current javascript file name
问题描述
我有一个名为 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.
当前正在执行的包含文件将始终是<$中的最后一个c $ c>脚本数组。所以你可以在 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.
这篇关于如何获取当前javascript文件名的绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!