--- title: document.currentScript slug: Web/API/Document/currentScript tags: - API - DOM - Property - Reference - 参考 - 属性 translation_of: Web/API/Document/currentScript ---
Document.currentScript 属性返回当前正在运行的脚本所属的 {{HTMLElement("script")}} 元素。调用此属性的脚本不能是 JavaScript 模块,模块应当使用 {{JSxRef("Statements/import%2Emeta", "import.meta")}} 对象。
值得注意的是,如果当前正在执行的代码是被其他代码作为回调函数或者事件处理函数调用的,那么 currentScript 属性不会指向任何 {{HTMLElement("script")}} 元素,而是会返回 null。这个属性只在脚本被解析后首次运行时有效。
var curScriptElement = document.currentScript;
下例演示了如何检测当前正在执行脚本的 {{HTMLElement("script")}} 元素是否是以异步模式执行的。
if (document.currentScript.async) {
console.log("Executing asynchronously");
} else {
console.log("Executing synchronously");
}
| 规范 | 状态 | 备注 |
|---|---|---|
| {{SpecName("HTML WHATWG", "dom.html#dom-document-currentscript", "Document.currentScript")}} | {{Spec2("HTML WHATWG")}} | Initial definition |