可能重复:
How may I reference the script tag that loaded the currently-executing script?
Can you select the script element that included the JavaScript?
是否有identifyScript
可以使这项工作? jQuery也很酷。:
<script type="text/javascript" id="script1">
function identifyScript(){...}
</script>
<script type="text/javascript" id="script1">
identifyScript(); //This function would alert "script1"
</script>
<script type="text/javascript" id="script2">
identifyScript(); //This function would alert "script2"
</script>
答案 0 :(得分:5)
只要保证脚本文件按顺序加载(即不异步),就可以在每个javascript文件中调用以下代码:
var scripts = document.getElementsByTagName( 'script' ),
lastTag = scripts[ scripts.length - 1 ];
alert( lastTag.id );
但是,只要这些async
元素中存在defer
或<script>
属性,此概念就会中断。这些属性中的每一个都允许浏览器延迟脚本的加载,并且不再保证订单。
但是如果您在没有任何 async 标志的情况下加载文件,这将正常工作,因为每个脚本都访问最后插入的<script>
节点,该节点必须是加载的节点从
答案 1 :(得分:0)
<script type="text/javascript">
function identifyScript() {
scripts = document.getElementsByTagName("script");
alert(scripts[scripts.length - 1].id);
}
</script>
<script type="text/javascript" id="script1">
identifyScript(); //This function would alert "script1"
</script>
<script type="text/javascript" id="script2">
identifyScript(); //This function would alert "script2"
</script>
这是有效的,因为当它在每个块中运行时,该块是最后一个存在,所以它是集合中的最后一个。