JavaScript:获取当前执行的< script>节点? [英] JavaScript: get the current executing <script> node?
问题描述
我需要知道是否可以获取当前的执行节点?
I need to know if it is possible to obtain the current execution node?
示例:
..html
<script id="x">
console.log(document.currentNode.id); // << this must return "x"
</script>
..html
谢谢!
推荐答案
我不知道100%的确定,但是由 document.getElementsByTagName('script')返回的脚本标签的集合
不应该包含低于当前正在执行的< script>
的脚本标签。换句话说,我认为这应该工作:
I don't know for 100% sure, but the collection of script tags returned by document.getElementsByTagName('script')
should not include the script tags that are below the presently executing <script>
. In other words, I think that this should work:
var arrScripts = document.getElementsByTagName('script');
var strScriptTagId = arrScripts[arrScripts.length - 1].id;
这只适用于在页面加载时正在执行的脚本。如果这在延迟脚本中执行或作为页面加载事件的一部分执行,则可能会始终在完全呈现的页面中报告最后一个< script>
。请注意,id标签不是< script>
的有效属性,因此您的页面将不会验证。如果您有任何外部脚本编写脚本标签(例如第三方广告),我认为代码将是不可预测的。我在几年前和这个想法一起玩,结果不能令人满意。
This will only work for scripts that are executing as the page loads. If this executes in a deferred script or as part of a page-load event, it will likely always report the last <script>
in the completely rendered page. Note that the id tag is not a valid attribute for <script>
, so your page won't likely validate. If you have any external scripts that write script tags (for example, third party ads), I think the code will be unpredictable. I played with this idea a couple years ago and the results were unsatisfactory.
这篇关于JavaScript:获取当前执行的< script>节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!