Document.currentScript - 実行中のスクリプト
currentScriptは、Documentのプロパティです。現在、処理を実行しているscript要素を返します。存在しない場合、値はnullになります。
概要
- 名前
- currentScript
- 所属
- Document
- IDL
readonly attribute HTMLOrSVGScriptElement? currentScript; // classic scripts in a document tree only typedef (HTMLScriptElement or SVGScriptElement) HTMLOrSVGScriptElement;
- 仕様書
- https://html.spec.whatwg.org/multipage/dom.html#dom-document-currentscript
説明
処理を実行中のscript要素を返す。処理が要素に属していない場合はnullを返す。
チュートリアル
Document.currentScriptは、script要素を返します。例えば、下記の場合はscript#hogeが返ります。
<script id="hoge">
// プロパティの取得
var result = document.currentScript ; // script#hoge
</script>
しかし、下記の場合はnullが返ります。これは、script#hogeが実行したのは、あくまでWindow.setTimeout()だからです。「〜秒後に関数を実行する設定はしたけど、その関数を実行しているのは自分じゃない」という理屈です。Window.setInterval()などでも同様です。
<script id="hoge">
setTimeout( function () {
// プロパティの取得
var result = document.currentScript ; // null
}, 100 ) ;
</script>
デモ
Document.currentScriptのデモです。
<!-- このコードは編集できます。 -->
<!DOCTYPE html>
<html>
<body>
<script id="syncer">
var value = document.currentScript ;
console.log( value ) ;
document.body.appendChild( new Text( value ) ) ;
</script>
</body>
</html>
サポート状況
Chrome | Firefox | Safari | Edge | IE | Opera | iOS Safari | Android |
---|---|---|---|---|---|---|---|
● 29+ | ● | ● 7.1+ | ● | × | ● 16+ | ● 8.3+ | ● 4.4+ |
関連記事
- ページのURLを取得する
- ページのURLを取得するには、locationオブジェクトの各プロパティを参照します。
- Document.scrollingElement
- scrollingElementは、Documentのプロパティです。ドキュメントの、スクロール対象の要素を返します。基本的にbody要素、それがなければhtml要素、それもなければnullを返します。
- Document.adoptNode()
- adoptNode()は、Documentのメソッドです。外部のドキュメントから自身のドキュメントにノードを移動します。元のノードはなくなります。
- Document.readyState
- readyStateは、Documentのプロパティです。ドキュメントの読み込み状況を表す文字列を返します。