Document.currentScript
属性返回当前正在运行的脚本所属的 <script>
元素。调用此属性的脚本不能是 JavaScript 模块,模块应当使用 import.meta
对象。
值得注意的是,如果当前正在执行的代码是被其他代码作为回调函数或者事件处理函数调用的,那么 currentScript
属性不会指向任何 <script>
元素,而是会返回 null
。这个属性只在脚本被解析后首次运行时有效。
语法
var curScriptElement = document.currentScript;
示例
下例演示了如何检测当前正在执行脚本的 <script>
元素是否是以异步模式执行的。
if (document.currentScript.async) {
console.log("Executing asynchronously");
} else {
console.log("Executing synchronously");
}
规范
规范 | 状态 | 备注 |
---|---|---|
HTML Living Standard Document.currentScript |
Living Standard | Initial definition |
浏览器兼容性
BCD tables only load in the browser
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.