更新时间:2023-12-04 18:24:41
document.currentScript
document.currentScript
将返回当前正在处理其脚本的 元素.
<script>
var me = document.currentScript;
</script>
defer
& async
)
为脚本提供一个 id 属性,让您可以使用 document.getElementById()
.
Giving the script an id attribute will let you easily select it by id from within using document.getElementById()
.
<script id="myscript">
var me = document.getElementById('myscript');
</script>
defer
& async
)id
属性可能会导致某些浏览器中的脚本在某些边缘情况下出现奇怪的行为id
attribute may cause weird behaviour for scripts in some browsers for some edge cases给脚本一个 data-*
属性将让您轻松地从内部选择它.
Giving the script a data-*
attribute will let you easily select it from within.
<script data-name="myscript">
var me = document.querySelector('script[data-name="myscript"]');
</script>
与前一个选项相比,这几乎没有什么好处.
This has few benefits over the previous option.
defer
& async
)querySelector()
不适用于所有浏览器id
属性得到广泛支持
和 id
边缘情况.querySelector()
not compliant in all browsersid
attribute<script>
with id
edge cases. 您可以使用选择器按来源选择脚本,而不是使用数据属性:
Instead of using the data attributes, you can use the selector to choose the script by source:
<script src="//example.com/embed.js"></script>
在 embed.js 中:
In embed.js:
var me = document.querySelector('script[src="//example.com/embed.js"]');
defer
& async
)id
属性得到广泛支持id
attribute我们还可以遍历每个脚本元素并单独检查每个元素以选择我们想要的:
We can also loop over every script element and check each individually to select the one we want:
<script>
var me = null;
var scripts = document.getElementsByTagName("script")
for (var i = 0; i < scripts.length; ++i) {
if( isMe(scripts[i])){
me = scripts[i];
}
}
</script>
这让我们可以在不支持 querySelector()
属性的旧浏览器中使用之前的两种技术.例如:
This lets us use both previous techniques in older browsers that don't support querySelector()
well with attributes. For example:
function isMe(scriptElem){
return scriptElem.getAttribute('src') === "//example.com/embed.js";
}
这继承了任何方法的优点和问题,但不依赖于 querySelector()
,因此可以在旧浏览器中工作.
This inherits the benefits and problems of whatever approach is taken, but does not rely on querySelector()
so will work in older browsers.
由于脚本是按顺序执行的,最后一个脚本元素通常是当前正在运行的脚本:
Since the scripts are executed sequentially, the last script element will very often be the currently running script:
<script>
var scripts = document.getElementsByTagName( 'script' );
var me = scripts[ scripts.length - 1 ];
</script>
defer
& async
)defer
& async
)