SYNCERのロゴ
アイキャッチ画像

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>

サポート状況

ChromeFirefoxSafariEdgeIEOperaiOS SafariAndroid
29+ 7.1+× 16+ 8.3+ 4.4+
  • Twitterでシェア
  • Facebookでシェア
  • Google+でシェア
  • はてなブックマークでシェア
  • pocketに保存
  • LINEでシェア
更新履歴
2017年10月6日 (金)
コンテンツを公開しました。