blob: a54cb27eb83e2cbbf5ec8097e0e40c5b518b1949 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
---
title: document.currentScript
slug: Web/API/Document/currentScript
tags:
- API
- DOM
- Property
- Reference
- 参考
- 属性
translation_of: Web/API/Document/currentScript
---
<div>{{ApiRef("DOM")}}</div>
<p><code><strong>Document.currentScript</strong></code> 属性返回当前正在运行的脚本所属的 {{HTMLElement("script")}} 元素。调用此属性的脚本<a href="https://github.com/whatwg/html/issues/997">不能是 JavaScript 模块</a>,模块应当使用 {{JSxRef("Statements/import%2Emeta", "import.meta")}} 对象。</p>
<p>值得注意的是,如果当前正在执行的代码是被其他代码作为回调函数或者事件处理函数调用的,那么 <code>currentScript</code> 属性不会指向任何 {{HTMLElement("script")}} 元素,而是会返回 <code>null</code>。这个属性只在脚本被解析后首次运行时有效。</p>
<h2 id="语法">语法</h2>
<pre class="syntaxbox">var <var>curScriptElement</var> = <var>document</var>.currentScript;
</pre>
<h2 id="示例">示例</h2>
<p>下例演示了如何检测当前正在执行脚本的 {{HTMLElement("script")}} 元素是否是以异步模式执行的。</p>
<pre class="brush:js">if (document.currentScript.async) {
console.log("Executing asynchronously");
} else {
console.log("Executing synchronously");
}</pre>
<p><a href="/samples/html/currentScript.html">View Live Examples</a></p>
<h2 id="规范">规范</h2>
<table class="standard-table">
<thead>
<tr>
<th scope="col">规范</th>
<th scope="col">状态</th>
<th scope="col">备注</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{SpecName("HTML WHATWG", "dom.html#dom-document-currentscript", "Document.currentScript")}}</td>
<td>{{Spec2("HTML WHATWG")}}</td>
<td>Initial definition</td>
</tr>
</tbody>
</table>
<h2 id="浏览器兼容性">浏览器兼容性</h2>
<div>{{Compat("api.Document.currentScript")}}</div>
<h2 id="相关链接">相关链接</h2>
<ul>
<li>{{JSxRef("Statements/import%2Emeta", "import.meta")}}</li>
<li>{{HTMLElement("script")}}</li>
<li>{{DOMxRef("document.onafterscriptexecute")}}</li>
<li>{{DOMxRef("document.onbeforescriptexecute")}}</li>
</ul>
|