我很确定答案是否定的,但我想我还是会问.
如果我的站点引用了一个名为"whatever.js"的脚本,是否可以从该脚本中获取"whatever.js"?喜欢:
var scriptName = ???
if (typeof jQuery !== "function") {
throw new Error(
"jQuery's script needs to be loaded before " +
scriptName + ". Check the <script> tag order.");
}
Run Code Online (Sandbox Code Playgroud)
可能比依赖检查更值得麻烦,但是到底是怎么回事.
Sho*_*og9 33
var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
var scriptName = lastScript.src;
alert("loading: " + scriptName);
Run Code Online (Sandbox Code Playgroud)
测试:FF 3.0.8,Chrome 1.0.154.53,IE6
jdu*_*tor 20
我知道这已经过时了,但我已经开发出了更好的解决方案,因为上述所有内容都不适用于异步脚本.通过一些调整,以下脚本可以涵盖几乎所有用例.什么对我有用:
function getScriptName() {
var error = new Error()
, source
, lastStackFrameRegex = new RegExp(/.+\/(.*?):\d+(:\d+)*$/)
, currentStackFrameRegex = new RegExp(/getScriptName \(.+\/(.*):\d+:\d+\)/);
if((source = lastStackFrameRegex.exec(error.stack.trim())) && source[1] != "")
return source[1];
else if((source = currentStackFrameRegex.exec(error.stack.trim())))
return source[1];
else if(error.fileName != undefined)
return error.fileName;
}
Run Code Online (Sandbox Code Playgroud)
不确定Internet Explorer上的支持,但在我测试的其他所有浏览器中都能正常工作.
ale*_*lex 12
您可以使用...
var scripts = document.getElementsByTagName("script"),
currentScriptUrl = (document.currentScript || scripts[scripts.length - 1]).src;
Run Code Online (Sandbox Code Playgroud)
currentScript() 除了IE之外的所有浏览器都支持.
确保它在解析和执行文件时运行,而不是在DOM就绪或window加载时运行.
如果它是一个空字符串,则您的script块没有或没有空src属性.
在 Node.js 中:
var abc = __filename.split(__dirname+"/").pop();
Run Code Online (Sandbox Code Playgroud)
Shog9 的建议更短:
alert("loading: " + document.scripts[document.scripts.length-1].src);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36796 次 |
| 最近记录: |