1. 4.12 スクリプティング
      1. 4.12.1 script要素
        1. 4.12.1.1 Processing model
        2. 4.12.1.2 スクリプト言語
        3. 4.12.1.3 script要素のコンテンツの制約
        4. 4.12.1.4 外部スクリプトに対するインライン文書
        5. 4.12.1.5 Interaction of script elements and XSLT
      2. 4.12.2 noscript要素
      3. 4.12.3 template要素
        1. 4.12.3.1 Interaction of template elements with XSLT and XPath
      4. 4.12.4 slot要素

4.12 スクリプティング

スクリプトは著者が文書に双方向性を追加することを許可する。

著者は、宣言型のメカニズムがしばしばより保守しやすく、かつ多くのユーザーがスクリプトを無効としているため、可能であれば、スクリプトに宣言型の代替を使用するよう推奨される。

たとえば、より詳細な情報を表示するセクションを表示または非表示にするスクリプトを使用する代わりに、details要素を使用できる。

著者はまた、スクリプトのサポートがない状態でそれらのアプリケーションが行儀よくデグレードするよう推奨される。

たとえば、著者がテーブルヘッダーにおいてリンクに動的なテーブルの再ソートを提供する場合、リンクはまたサーバーからソートされたテーブルを要求することによって、スクリプトなしで機能させることができるかもしれない。

4.12.1 script要素

Element/script

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

HTMLScriptElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android37+Samsung Internet?Opera Android12.1+
カテゴリー
メタデータコンテンツ
フローコンテンツ
フレージングコンテンツ
スクリプトサポート要素
この要素を使用できるコンテキスト
メタデータコンテンツが期待される場所。
フレージングコンテンツが期待される場所。
スクリプトサポート要素が期待される場所。
コンテンツモデル
src属性が存在しない場合、type属性の値に依存するが、スクリプトの内容制限に一致しなければならない。
src属性が存在する場合、要素は空またはスクリプト文書を含むだけでなくスクリプトの内容制限に一致するかのいずれかでなければならない。
text/htmlにおけるタグ省略
どちらのタグも省略不可。
コンテンツ属性
グローバル属性
src — リソースのアドレス
type — スクリプトの種類
nomoduleモジュールスクリプトをサポートするユーザーエージェントにおける実行を防ぐ
async — フェッチの間ブロックなしで、可能な場合にスクリプトを実行する
defer — スクリプトの実行を延期する
crossorigin — 要素が生成元をまたいだ要求を処理する方法
integritySubresource Integrityチェックで使用される整合性メタデータ[SRI]
referrerpolicy — 要素によって開始されたフェッチのためのリファラーポリシー
blocking — 要素が潜在的にレンダリングブロッキングであるかどうか
fetchpriority — 要素によって開始されるフェッチ優先度を設定する
アクセシビリティの考慮
著者向け
実装者向け
DOMインターフェイス
[Exposed=Window]
interface HTMLScriptElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute USVString src;
  [CEReactions] attribute DOMString type;
  [CEReactions] attribute boolean noModule;
  [CEReactions] attribute boolean async;
  [CEReactions] attribute boolean defer;
  [CEReactions] attribute DOMString? crossOrigin;
  [CEReactions] attribute DOMString text;
  [CEReactions] attribute DOMString integrity;
  [CEReactions] attribute DOMString referrerPolicy;
  [SameObject, PutForwards=value] readonly attribute DOMTokenList blocking;
  [CEReactions] attribute DOMString fetchPriority;

  static boolean supports(DOMString type);

  // also has obsolete members
};

script要素は、著者が文書に動的スクリプトおよびデータブロックを含むことを許可する。この要素は、ユーザーにコンテンツを表すものでない。

Element/script#attr-type

Support in all current engines.

Firefox1+Safari≤4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

type属性は、表されるスクリプトの型をカスタマイズを可能にする:

データブロック妥当なMIMEタイプ文字列を使用して表記されなければならない要件は、潜在的な将来の衝突を回避するための場所である。この仕様がスクリプトの追加の型をいずれ追加する場合、その追加の型は"module"値がモジュールスクリプトを表す方法のように、MIMEタイプでない何かにtype属性を設定することによってトリガーされる。現在に妥当なMIMEタイプ文字列を使用することで、将来のユーザーエージェントでさえも、データブロックが異なるスクリプトタイプとして再解釈されないことを保証する。

クラシックスクリプトおよびJavaScriptモジュールスクリプトは、インラインで埋め込むかsrc属性を使用する外部ファイルからインポートすることができ、これは指定された場合に使用する外部スクリプトリソースのURLを与える。srcが指定される場合、潜在的にスペースで囲まれる妥当な空でないURLでなければならない。

インラインscript要素、または外部スクリプトリソースのコンテンツは、それぞれクラシックスクリプトおよびJavaScriptモジュールスクリプトに対するJavaScript仕様のScriptまたはModule生成物の要件に適合しなければならない。[JAVASCRIPT]

CSSモジュールスクリプトの外部スクリプトリソースのコンテンツは、CSS仕様の要件に準拠しなければならない。[CSS]

The contents of the external script resource for JSON module scripts must conform to the requirements of the JSON specification. [JSON]

インポートマップのインラインscript要素のコンテンツは、インポートマップのオーサリング要件に適合しなければならない。

インポートマップscript要素の場合、srcasyncnomoduledefercrossoriginintegrityおよび referrerpolicy属性を指定してはならない。

1つの文書は、複数のインポートマップscript要素を持ってはならない。

データブロックを含めるために使用される場合、データは、インラインに埋め込まれなければならず、データの形式は、type属性を使用して指定しなければならず、かつscript要素のコンテンツは、使用される形式のために定義される要件に適合しなければならない。srcasyncnomoduledefercrossoriginintegrityreferrerpolicyおよびfetchpriority属性を指定してはならない。

nomodule属性は、モジュールスクリプトをサポートするユーザーエージェントでスクリプトが実行されないようにする真偽属性である。これは、以下に示すように、モダンなユーザーエージェントのモジュールスクリプトと古いユーザーエージェントのクラシックスクリプトの選択的な実行を可能にする。nomodule属性をモジュールスクリプトで指定してはならない(この属性がある場合は無視される)。

Element/script#attr-async

Support in all current engines.

Firefox1+Safari≤4+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

Element/script#attr-defer

Support in all current engines.

Firefox3.5+Safari3+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

asyncおよびdefer属性は、どのようにスクリプトが評価されるべきかを示す真偽属性である。クラシックスクリプトは、deferまたはasyncを指定してもよいが、src属性が存在しない限り、いずれかを指定してはならない。モジュールスクリプトasync属性を指定してもよいが、defer属性を指定してはならない。

これらの属性を使用して、スクリプトの種類によって選択できる複数の可能なモードが存在する。

クラシックスクリプトについて、async属性が存在する場合、クラシックスクリプトは、構文解析と並行してフェッチされるとすぐに(潜在的に構文解析が完了する前に)利用可能になると評価される。asyncが存在しないがdefer属性が存在する場合、クラシックスクリプトは、並行してフェッチされ、ページが解析終了したときに評価される。いずれの属性も存在しない場合、スクリプトは、両方が完了するまで解析を阻止して、すぐにフェッチされ評価される。

モジュールスクリプトについて、async属性が存在する場合、モジュールスクリプトとそのすべての依存関係は、構文解析と並行してフェッチされ、モジュールスクリプトは利用可能になるとすぐに(潜在的に構文解析が完了する前に)評価される。そうでなければ、モジュールスクリプトとその依存関係は、構文解析と並行してフェッチされ、ページが解析終了したときに評価される。(defer属性は、モジュールスクリプトに影響しない。)

これは、次の模式図にすべて要約される:

<script>のために、解析はフェッチと実行によって中断される。With <script defer>, fetching is parallel to parsing and execution takes place after all parsing has finished. And with <script async>, fetching is parallel to parsing but once it finishes parsing is interrupted to execute the script. <script type=module>のストーリーは<script defer>に似ているが、依存関係もフェッチされ、<script type=module async>のストーリーは追加の依存関係のフェッチを伴う<script async>に似ている。

これら属性の正確な処理の詳細は、主に歴史的な理由から、いくぶん自明でない、多くのHTMLの側面を含む。したがって、実装要求は必然的に仕様のあらゆる場所に散在している。(この節の)下記のアルゴリズムは、この処理の中核を説明するが、これらのアルゴリズムが参照する、およびHTMLにおけるscript開始タグと終了タグに対する構文解析規則、無関係なコンテンツでXMLでdocument.write()メソッドに対する規則、スクリプトの取り扱いなどによって参照される。

document.write()メソッドを使用して挿入するとき、通常はscript要素が実行される(一般に、スクリプトの実行またはHTMLの解析をブロックする)。innerHTML属性とouterHTML属性を使用して挿入する場合、それらは一切実行されない。

たとえasync属性が指定されても、デフォルトとなるブロッキング動作の代わりにdeferの動作をフォールバックするために、deferのみをサポートする(かつasyncをサポートしない)レガシーウェブブラウザーをもたらすため、defer属性は指定されてもよい。

crossorigin属性はCORS設定属性である。クラシックスクリプトについて、スクリプトが他の生成元から得られる場合、エラー情報が公開されるかどうかを制御する。モジュールスクリプトについて、生成元をまたいだリクエストに使用される資格情報モードを制御する。

クラシックスクリプトとは異なり、モジュールスクリプトは、生成元をまたいだフェッチのためにCORSプロトコルを使用する必要がある。

integrity属性は、この要素が責任を負うリクエストに対する完全性メタデータを表す。値はテキストである。src属性が指定されていない場合、integrity属性は指定してはならない。[SRI]

referrerpolicy属性は、リファラーポリシー属性である。その目的は、スクリプトをフェッチするときに使用されるリファラーポリシーと、そこからインポートされたスクリプトを設定することにある。[REFERRERPOLICY]

インポートされたスクリプトをフェッチするときに使用されているが他のサブリソースを取得していないときに使用されているscriptのリファラーポリシーの例:

<script referrerpolicy="origin">
  fetch('/api/data');    // not fetched with <script>'s referrer policy
  import('./utils.mjs'); // is fetched with <script>'s referrer policy ("origin" in this case)
</script>

blocking属性はブロッキング属性である。

fetchpriorityは、フェッチ優先度属性である。その目的は、スクリプトをフェッチするときに使用される優先順位を設定することである。

srctypenomoduleasyncdefercrossoriginintegrityreferrerpolicyfetchpriority属性を動的に変更しても、直接的な影響はない。これらの属性は、下記の特定の時間でのみ使用される。

The IDL attributes src, type, defer, integrity, and blocking, must each reflect the respective content attributes of the same name.

HTMLScriptElement/referrerPolicy

Support in all current engines.

Firefox65+Safari14+Chrome70+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

The referrerPolicy IDL attribute must reflect the referrerpolicy content attribute, limited to only known values.

The fetchPriority IDL attribute must reflect the fetchpriority content attribute, limited to only known values.

The crossOrigin IDL attribute must reflect the crossorigin content attribute, limited to only known values.

The noModule IDL attribute must reflect the nomodule content attribute.

The async getter steps are:

  1. If this's force async is true, then return true.

  2. If this's async content attribute is present, then return true.

  3. falseを返す。

The async setter steps are:

  1. Set this's force async to false.

  2. If the given value is true, then set this's async content attribute to the empty string.

  3. Otherwise, remove this's async content attribute.

script.text [ = value ]

要素の子テキストコンテンツを返す。

与えられた値を持つ要素の子を置換するために、設定できる。

HTMLScriptElement.supports(type)

指定されたtypeがユーザーエージェントによってサポートされるスクリプトタイプである場合、trueを返す。この仕様で可能なスクリプトタイプは"classic"、"module"および"importmap"であるが、将来的に他のタイプが追加される可能性がある。

The text attribute's getter must return this script element's child text content.

The text attribute's setter must string replace all with the given value within this script element.

HTMLScriptElement/supports_static

Support in all current engines.

Firefox94+Safari16+Chrome96+
Opera?Edge96+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

supports(type)メソッドのステップは次のとおり:

  1. type"classic"である場合、trueを返す。

  2. type"module"である場合、trueを返す。

  3. If type is "importmap", then return true.

  4. falseを返す。

type引数は、これらの値と正確に一致する必要がある。ASCII大文字・小文字不区別一致は実行しない。これは、typeコンテンツ属性値の処理方法、およびDOMTokenListsupports()メソッドの動作とは異なるが、Worker()コンストラクターで使用されるWorkerType列挙体と一致する。

次の例において、2つのscript要素が使用される。1つは外部のクラシックスクリプトを埋め込み、もう1つはデータブロックのようないくつかのデータを含む。

<script src="game-engine.js"></script>
<script type="text/x-game-map">
........U.........e
o............A....e
.....A.....AAA....e
.A..AAA...AAAAA...e
</script>

この場合のデータは、ビデオゲームのマップを生成するスクリプトによって使用されるかもしれない。しかし、データはそのように使用する必要はない。おそらく実際にマップデータは、ページのマークアップの他の部分に埋め込まれており、ここでデータブロックは、ゲームマップで特定の機能を探しているユーザーを支援するサイトの検索エンジンによって単に使用される。

次のサンプルは、script要素が外部モジュールスクリプトを含めるために使用される方法を示す。また、フォームの出力を初期化する場合に、文書が解析されている間にscript要素がスクリプトを呼び出すために使用されうる方法を示す。

<script>
 function calculate(form) {
   var price = 52000;
   if (form.elements.brakes.checked)
     price += 1000;
   if (form.elements.radio.checked)
     price += 2500;
   if (form.elements.turbo.checked)
     price += 5000;
   if (form.elements.sticker.checked)
     price += 250;
   form.elements.result.value = price;
 }
</script>
<form name="pricecalc" onsubmit="return false" onchange="calculate(this)">
 <fieldset>
  <legend>Work out the price of your car</legend>
  <p>Base cost: £52000.</p>
  <p>Select additional options:</p>
  <ul>
   <li><label><input type=checkbox name=brakes> Ceramic brakes (£1000)</label></li>
   <li><label><input type=checkbox name=radio> Satellite radio (£2500)</label></li>
   <li><label><input type=checkbox name=turbo> Turbo charger (£5000)</label></li>
   <li><label><input type=checkbox name=sticker> "XZ" sticker (£250)</label></li>
  </ul>
  <p>Total: £<output name=result></output></p>
 </fieldset>
 <script>
  calculate(document.forms.pricecalc);
 </script>
</form>

次のサンプルは、script要素が外部JavaScriptモジュールスクリプトを含めるために使用される方法を示す。

<script type="module" src="app.mjs"></script>

このモジュール、およびそのすべての依存関係(ソースファイル内のJavaScript import文を通して表現される)は、フェッチされる。一度、全体の結果としてモジュールグラフがインポートされ、かつ文書が解析を完了したら、app.mjsのコンテンツは評価される。

さらに、同じWindow内の他のscript要素からのコードがapp.mjsからモジュールをインポートする場合(たとえばimport "./app.mjs";経由で)、より早いscript要素によって作成された同じJavaScriptモジュールスクリプトがインポートされる。

次の例は、モダンなユーザーエージェント用のJavaScriptモジュールスクリプトと古いユーザーエージェント用のクラシックスクリプトを含める方法を示している:

<script type="module" src="app.mjs"></script>
<script nomodule defer src="classic-app-bundle.js"></script>

JavaScriptモジュールスクリプトをサポートするモダンなユーザーエージェントでは、nomodule属性を持つscript要素は無視され、"module"のtypeをもつscript要素がフェッチされ、評価される(モジュールスクリプトとして)。逆に、古いユーザーエージェントは、"module"のtypeをもつscript要素を、そのスクリプトタイプを未知のものとして無視するが、nomodule属性を実装しないため、他のscript要素を(クラシックスクリプトとして)フェッチして評価することは問題ない。

次のサンプルは、script要素が(たとえばニュースサイト上で)より面白い読書体験を生み出すために、文書のテキストで多数の置換を行うインラインJavaScriptモジュールスクリプトを書くために使用することができる方法を示す:[XKCD1288]

<script type="module">
 import { walkAllTextNodeDescendants } from "./dom-utils.mjs";

 const substitutions = new Map([
   ["witnesses", "these dudes I know"]
   ["allegedly", "kinda probably"]
   ["new study", "Tumblr post"]
   ["rebuild", "avenge"]
   ["space", "spaaace"]
   ["Google glass", "Virtual Boy"]
   ["smartphone", "Pokédex"]
   ["electric", "atomic"]
   ["Senator", "Elf-Lord"]
   ["car", "cat"]
   ["election", "eating contest"]
   ["Congressional leaders", "river spirits"]
   ["homeland security", "Homestar Runner"]
   ["could not be reached for comment", "is guilty and everyone knows it"]
 ]);

 function substitute(textNode) {
   for (const [before, after] of substitutions.entries()) {
     textNode.data = textNode.data.replace(new RegExp(`\\b${before}\\b`, "ig"), after);
   }
 }

 walkAllTextNodeDescendants(document.body, substitute);
</script>

JavaScriptモジュールスクリプトを使用して得られたいくつかの注目すべき機能は、他のJavaScriptモジュール、デフォルトでstrictモード、およびトップレベル宣言がグローバルオブジェクトに新しいプロパティを導入しない方法から関数をインポートする機能を含む。両方の文書の解析が完了し、およびその依存関係(dom-utils.mjs)がフェッチされかつ評価されるまで、このscript要素が文書に表示されるかを問わず、評価されないことにも注意する。

次の例は、JSONモジュールスクリプトJavaScriptモジュールスクリプト内からインポートする方法を示す:

<script type="module">
 import peopleInSpace from "http://api.open-notify.org/astros.json" with { type: "json" };

 const list = document.querySelector("#people-in-space");
 for (const { craft, name } of peopleInSpace.people) {
   const li = document.createElement("li");
   li.textContent = `${name} / ${craft}`;
   list.append(li);
 }
</script>

モジュールスクリプトのMIMEタイプチェックは厳密である。JSONモジュールスクリプトのフェッチを成功させるために、HTTPレスポンスがJSON MIMEタイプContent-Type: text/jsonなど)を持たなければならない。一方、ステートメントのwith { type: "json" }の部分が省略される場合、JavaScriptモジュールスクリプトをインポートすることが目的であるとみなされ、HTTPレスポンスがJavaScript MIMEタイプでないMIMEタイプを持つ場合にフェッチが失敗する。

4.12.1.1 Processing model

A script element has several associated pieces of state.

A script element has a parser document, which is either null or a Document, initially null. It is set by the HTML parser and the XML parser on script elements they insert, and affects the processing of those elements. script elements with non-null parser documents are known as parser-inserted.

A script element has a preparation-time document, which is either null or a Document, initially null. It is used to prevent scripts that move between documents during preparation from executing.

A script element has a force async boolean, initially true. It is set to false by the HTML parser and the XML parser on script elements they insert, and when the element gets an async content attribute added.

A script element has a from an external file boolean, initially false. It is determined when the script is prepared, based on the src attribute of the element at that time.

A script element has a ready to be parser-executed boolean, initially false. This is used only used for elements that are also parser-inserted, to let the parser know when to execute the script.

A script element has an already started boolean, initially false.

A script element has a delaying the load event boolean, initially false.

A script element has a type, which is either null, "classic", "module", or "importmap", initially null. It is determined when the element is prepared, based on the type attribute of the element at that time.

A script element has a result, which is either "uninitialized", null (representing an error), a script, or an import map parse result. It is initially "uninitialized".

A script element has steps to run when the result is ready, which are a series of steps or null, initially null. To mark as ready a script element el given a script, import map parse result, or null result:

  1. Set el's result to result.

  2. If el's steps to run when the result is ready are not null, then run them.

  3. Set el's steps to run when the result is ready to null.

  4. Set el's delaying the load event to false.


A script element el is implicitly potentially render-blocking if el's type is "classic", el is parser-inserted, and el does not have an async or defer attribute.

The cloning steps for a script element el being cloned to a copy copy are to set copy's already started to el's already started.

When an async attribute is added to a script element el, the user agent must set el's force async to false.

Whenever a script element el's delaying the load event is true, the user agent must delay the load event of el's preparation-time document.


When a script element el that is not parser-inserted experiences one of the events listed in the following list, the user agent must immediately prepare the script element el:

To prepare the script element given a script element el:

  1. If el's already started is true, then return.

  2. Let parser document be el's parser document.

  3. Set el's parser document to null.

    This is done so that if parser-inserted script elements fail to run when the parser tries to run them, e.g. because they are empty or specify an unsupported scripting language, another script can later mutate them and cause them to run again.

  4. If parser document is non-null and el does not have an async attribute, then set el's force async to true.

    This is done so that if a parser-inserted script element fails to run when the parser tries to run it, but it is later executed after a script dynamically updates it, it will execute in an async fashion even if the async attribute isn't set.

  5. Let source text be el's child text content.

  6. If el has no src attribute, and source text is the empty string, then return.

  7. If el is not connected, then return.

  8. If any of the following are true:

    then let the script block's type string for this script element be "text/javascript".

    Otherwise, if el has a type attribute, then let the script block's type string be the value of that attribute with leading and trailing ASCII whitespace stripped.

    Otherwise, el has a non-empty language attribute; let the script block's type string be the concatenation of "text/" and the value of el's language attribute.

    The language attribute is never conforming, and is always ignored if there is a type attribute present.

  9. If the script block's type string is a JavaScript MIME type essence match, then set el's type to "classic".

  10. Otherwise, if the script block's type string is an ASCII case-insensitive match for the string "module", then set el's type to "module".

  11. Otherwise, if the script block's type string is an ASCII case-insensitive match for the string "importmap", then set el's type to "importmap".

  12. Otherwise, return. (No script is executed, and el's type is left as null.)

  13. If parser document is non-null, then set el's parser document back to parser document and set el's force async to false.

  14. Set el's already started to true.

  15. Set el's preparation-time document to its node document.

  16. If parser document is non-null, and parser document is not equal to el's preparation-time document, then return.

  17. If scripting is disabled for el, then return.

    The definition of scripting is disabled means that, amongst others, the following scripts will not execute: scripts in XMLHttpRequest's responseXML documents, scripts in DOMParser-created documents, scripts in documents created by XSLTProcessor's transformToDocument feature, and scripts that are first inserted by a script into a Document that was created using the createDocument() API. [XHR] [DOMPARSING] [XSLTP] [DOM]

  18. If el has a nomodule content attribute and its type is "classic", then return.

    This means specifying nomodule on a module script has no effect; the algorithm continues onward.

  19. If el does not have a src content attribute, and the Should element's inline behavior be blocked by Content Security Policy? algorithm returns "Blocked" when given el, "script", and source text, then return. [CSP]

  20. If el has an event attribute and a for attribute, and el's type is "classic", then:

    1. Let for be the value of el's' for attribute.

    2. Let event be the value of el's event attribute.

    3. Strip leading and trailing ASCII whitespace from event and for.

    4. If for is not an ASCII case-insensitive match for the string "window", then return.

    5. If event is not an ASCII case-insensitive match for either the string "onload" or the string "onload()", then return.

  21. If el has a charset attribute, then let encoding be the result of getting an encoding from the value of the charset attribute.

    If el does not have a charset attribute, or if getting an encoding failed, then let encoding be el's node document's the encoding.

    If el's type is "module", this encoding will be ignored.

  22. Let classic script CORS setting be the current state of el's crossorigin content attribute.

  23. Let module script credentials mode be the CORS settings attribute credentials mode for el's crossorigin content attribute.

  24. Let cryptographic nonce be el's [[CryptographicNonce]] internal slot's value.

  25. If el has an integrity attribute, then let integrity metadata be that attribute's value.

    Otherwise, let integrity metadata be the empty string.

  26. Let referrer policy be the current state of el's referrerpolicy content attribute.

  27. Let fetch priority be the current state of el's fetchpriority content attribute.

  28. Let parser metadata be "parser-inserted" if el is parser-inserted, and "not-parser-inserted" otherwise.

  29. Let options be a script fetch options whose cryptographic nonce is cryptographic nonce, integrity metadata is integrity metadata, parser metadata is parser metadata, credentials mode is module script credentials mode, referrer policy is referrer policy, and fetch priority is fetch priority.

  30. Let settings object be el's node document's relevant settings object.

  31. If el has a src content attribute, then:

    1. If el's type is "importmap", then queue an element task on the DOM manipulation task source given el to fire an event named error at el, and return.

      External import map scripts are not currently supported. See WICG/import-maps issue #235 for discussions on adding support.

    2. Let src be the value of el's src attribute.

    3. If src is the empty string, then queue an element task on the DOM manipulation task source given el to fire an event named error at el, and return.

    4. Set el's from an external file to true.

    5. Let url be the result of encoding-parsing a URL given src, relative to el's node document.

    6. If url is failure, then queue an element task on the DOM manipulation task source given el to fire an event named error at el, and return.

    7. If el is potentially render-blocking, then block rendering on el.

    8. Set el's delaying the load event to true.

    9. If el is currently render-blocking, then set options's render-blocking to true.

    10. Let onComplete given result be the following steps:

      1. Mark as ready el given result.

    11. Switch on el's type:

      "classic"

      Fetch a classic script given url, settings object, options, classic script CORS setting, encoding, and onComplete.

      "module"

      Fetch an external module script graph given url, settings object, options, and onComplete.

      For performance reasons, user agents may start fetching the classic script or module graph (as defined above) as soon as the src attribute is set, instead, in the hope that el will become connected (and that the crossorigin attribute won't change value in the meantime). Either way, once el becomes connected, the load must have started as described in this step. If the UA performs such prefetching, but el never becomes connected, or the src attribute is dynamically changed, or the crossorigin attribute is dynamically changed, then the user agent will not execute the script so obtained, and the fetching process will have been effectively wasted.

  32. If el does not have a src content attribute:

    1. Let base URL be el's node document's document base URL.

    2. Switch on el's type:

      "classic"
      1. Let script be the result of creating a classic script using source text, settings object, base URL, and options.

      2. Mark as ready el given script.

      "module"
      1. Set el's delaying the load event to true.

      2. If el is potentially render-blocking, then:

        1. Block rendering on el.

        2. Set options's render-blocking to true.

      3. Fetch an inline module script graph, given source text, base URL, settings object, options, and with the following steps given result:

        1. Mark as ready el given result.

      "importmap"
      1. If el's relevant global object's import maps allowed is false, then queue an element task on the DOM manipulation task source given el to fire an event named error at el, and return.

      2. Set el's relevant global object's import maps allowed to false.

      3. Let result be the result of creating an import map parse result given source text and base URL.

      4. Mark as ready el given result.

  33. If el's type is "classic" and el has a src attribute, or el's type is "module":

    1. Assert: el's result is "uninitialized".

    2. If el has an async attribute or el's force async is true:

      1. Let scripts be el's preparation-time document's set of scripts that will execute as soon as possible.

      2. Append el to scripts.

      3. Set el's steps to run when the result is ready to the following:

        1. Execute the script element el.

        2. Remove el from scripts.

    3. Otherwise, if el is not parser-inserted:

      1. Let scripts be el's preparation-time document's list of scripts that will execute in order as soon as possible.

      2. Append el to scripts.

      3. Set el's steps to run when the result is ready to the following:

        1. If scripts[0] is not el, then abort these steps.

        2. While scripts is not empty, and scripts[0]'s result is not "uninitialized":

          1. Execute the script element scripts[0].

          2. Remove scripts[0].

    4. Otherwise, if el has a defer attribute or el's type is "module":

      1. Append el to its parser document's list of scripts that will execute when the document has finished parsing.

      2. Set el's steps to run when the result is ready to the following: set el's ready to be parser-executed to true. (The parser will handle executing the script.)

    5. Otherwise:

      1. Set el's parser document's pending parsing-blocking script to el.

      2. Block rendering on el.

      3. Set el's steps to run when the result is ready to the following: set el's ready to be parser-executed to true. (The parser will handle executing the script.)

  34. Otherwise:

    1. Assert: el's result is not "uninitialized".

    2. If all of the following are true:

      then:

      1. Set el's parser document's pending parsing-blocking script to el.

      2. Set el's ready to be parser-executed to true. (The parser will handle executing the script.)

    3. Otherwise, immediately execute the script element el, even if other scripts are already executing.

Each Document has a pending parsing-blocking script, which is a script element or null, initially null.

Each Document has a set of scripts that will execute as soon as possible, which is a set of script elements, initially empty.

Each Document has a list of scripts that will execute in order as soon as possible, which is a list of script elements, initially empty.

Each Document has a list of scripts that will execute when the document has finished parsing, which is a list of script elements, initially empty.

If a script element that blocks a parser gets moved to another Document before it would normally have stopped blocking that parser, it nonetheless continues blocking that parser until the condition that causes it to be blocking the parser no longer applies (e.g., if the script is a pending parsing-blocking script because the original Document has a style sheet that is blocking scripts when it was parsed, but then the script is moved to another Document before the blocking style sheet(s) loaded, the script still blocks the parser until the style sheets are all loaded, at which time the script executes and the parser is unblocked).

To execute the script element given a script element el:

  1. Let document be el's node document.

  2. If el's preparation-time document is not equal to document, then return.

  3. Unblock rendering on el.

  4. If el's result is null, then fire an event named error at el, and return.

  5. If el's from an external file is true, or el's type is "module", then increment document's ignore-destructive-writes counter.

  6. Switch on el's type:

    "classic"
    1. Let oldCurrentScript be the value to which document's currentScript object was most recently set.

    2. If el's root is not a shadow root, then set document's currentScript attribute to el. Otherwise, set it to null.

      This does not use the in a document tree check, as el could have been removed from the document prior to execution, and in that scenario currentScript still needs to point to it.

    3. Run the classic script given by el's result.

    4. Set document's currentScript attribute to oldCurrentScript.

    "module"
    1. Assert: document's currentScript attribute is null.

    2. Run the module script given by el's result.

    "importmap"
    1. Register an import map given el's relevant global object and el's result.

  7. Decrement the ignore-destructive-writes counter of document, if it was incremented in the earlier step.

  8. If el's from an external file is true, then fire an event named load at el.

4.12.1.2 スクリプト言語

User agents are not required to support JavaScript. This standard needs to be updated if a language other than JavaScript comes along and gets similar wide adoption by web browsers. Until such a time, implementing other languages is in conflict with this standard, given the processing model defined for the script element.

サーバーは、Updates to ECMAScript Media Typesに従って、JavaScriptリソースにtext/javascriptを使用すべきですある。サーバーは、JavaScriptリソースに他のJavaScript MIMEタイプを使用すべきではなく、非JavaScript MIMEタイプを使用してはならない。[RFC9239]

For external JavaScript resources, MIME type parameters in `Content-Type` headers are generally ignored. (In some cases the `charset` parameter has an effect.) However, for the script element's type attribute they are significant; it uses the JavaScript MIME type essence match concept.

For example, scripts with their type attribute set to "text/javascript; charset=utf-8" will not be evaluated, even though that is a valid JavaScript MIME type when parsed.

Furthermore, again for external JavaScript resources, special considerations apply around `Content-Type` header processing as detailed in the prepare the script element algorithm and Fetch. [FETCH]

4.12.1.3 script要素のコンテンツの制約

この節で説明されるかなり奇妙な制約を回避する最も簡単で安全な方法は、以下のシーケンスが(たとえば文字列、正規表現、またはコメントなど)スクリプト内でリテラルに表示される場合に、ASCII大文字・小文字不区別で一致する"<!--"を"\x3C!--"として、"<script"を"\x3Cscript"として、および"</script"を"\x3C/script"として常にエスケープし、式の中でそのような構造体を使用してコードを記述するのを避けるようにすることである。この節の制限がトリガーになりやすい落とし穴を回避する:すなわち、歴史的な理由のために、HTMLにおけるscriptブロックの解析は、これらのシーケンスを考えた場合に直観的でない働きをする奇妙で風変わりな慣習である。

script要素の子孫テキストコンテンツは、Unicodeの文字セットである次のABNFのscript生成物と一致しなければならない。[ABNF]

script        = outer *( comment-open inner comment-close outer )

outer         = < any string that doesn't contain a substring that matches not-in-outer >
not-in-outer  = comment-open
inner         = < any string that doesn't contain a substring that matches not-in-inner >
not-in-inner  = comment-close / script-open

comment-open  = "<!--"
comment-close = "-->"
script-open   = "<" s c r i p t tag-end

s             =  %x0053 ; U+0053 LATIN CAPITAL LETTER S
s             =/ %x0073 ; U+0073 LATIN SMALL LETTER S
c             =  %x0043 ; U+0043 LATIN CAPITAL LETTER C
c             =/ %x0063 ; U+0063 LATIN SMALL LETTER C
r             =  %x0052 ; U+0052 LATIN CAPITAL LETTER R
r             =/ %x0072 ; U+0072 LATIN SMALL LETTER R
i             =  %x0049 ; U+0049 LATIN CAPITAL LETTER I
i             =/ %x0069 ; U+0069 LATIN SMALL LETTER I
p             =  %x0050 ; U+0050 LATIN CAPITAL LETTER P
p             =/ %x0070 ; U+0070 LATIN SMALL LETTER P
t             =  %x0054 ; U+0054 LATIN CAPITAL LETTER T
t             =/ %x0074 ; U+0074 LATIN SMALL LETTER T

tag-end       =  %x0009 ; U+0009 CHARACTER TABULATION (tab)
tag-end       =/ %x000A ; U+000A LINE FEED (LF)
tag-end       =/ %x000C ; U+000C FORM FEED (FF)
tag-end       =/ %x0020 ; U+0020 SPACE
tag-end       =/ %x002F ; U+002F SOLIDUS (/)
tag-end       =/ %x003E ; U+003E GREATER-THAN SIGN (>)

script要素がスクリプト文書を含む場合、以下の節で記述されるように、要素のコンテンツのさらなる制約がある。

以下のスクリプトは、この問題を示している。このように、文字列が含まれているスクリプトがあるとする:

const example = 'Consider this string: <!-- <script>';
console.log(example);

これがscriptブロックで直接この文字列を入れていた場合、上記の制限に違反しない。

<script>
  const example = 'Consider this string: <!-- <script>';
  console.log(example);
</script>

しかし、より大きな問題かつ、スクリプトがそれらの制限に違反しない理由は、実際にスクリプトが奇妙に解析されるだろうということである。上記のスクリプトブロックは終了していない。それは、実際には依然としてscriptブロックの一部であるこのスニペットにおいて"</script>"終了タグのように見えるものである。(スクリプトが終了していないため)スクリプトは実行しない。スクリプトが何らかの形で実行した場合、以下のようにマークアップが見えた場合、(ここで強調される)スクリプトが妥当なJavaScriptでないので、スクリプトは失敗するだろう:

<script>
  const example = 'Consider this string: <!-- <script>';
  console.log(example);
</script>
<!-- despite appearances, this is actually part of the script still! -->
<script>
 ... // this is the same script block still...
</script>

ここで起こっていることはレガシーな理由のために、HTMLにおけるscript要素で"<!--"および"<script"文字列は、パーサーがブロックを閉じる検討するためにバランスをとる必要がある。

この節の最初に述べたように、問題の文字列をエスケープすることによって、問題は完全に回避されている:

<script>
  // Note: `\x3C` is an escape sequence for `<`.
  const example = 'Consider this string: \x3C!-- \x3Cscript>';
  console.log(example);
</script>
<!-- this is just a comment between script blocks -->
<script>
 ... // this is a new script block
</script>

次の例のように、これらのシーケンスは自然にスクリプト式で出現可能である:

if (x<!--y) { ... }
if ( player<script ) { ... }

このような場合、文字はエスケープすることはできないが、シーケンスが発生しないように式は次のように書き換えることができる:

if (x < !--y) { ... }
if (!--y > x) { ... }
if (!(--y) > x) { ... }
if (player < script) { ... }
if (script > player) { ... }

これを行うとはまた、同様に様々な落とし穴を回避する:関連する歴史的な理由のために、クラシックスクリプトで文字列"<!--"は、"//"のように、実際には行コメントの開始として扱われる。

4.12.1.4 外部スクリプトに対するインライン文書

script要素のsrc属性が指定される場合、もしあれば、script要素のコンテンツは、要素のコンテンツから分割されるようなtext IDL属性値でなければならず、文字セットがUnicodeである下記のABNFでdocumentation生成物と一致しなければならない。[ABNF]

documentation = *( *( space / tab / comment ) [ line-comment ] newline )
comment       = slash star *( not-star / star not-slash ) 1*star slash
line-comment  = slash slash *not-newline

; characters
tab           = %x0009 ; U+0009 CHARACTER TABULATION (tab)
newline       = %x000A ; U+000A LINE FEED (LF)
space         = %x0020 ; U+0020 SPACE
star          = %x002A ; U+002A ASTERISK (*)
slash         = %x002F ; U+002F SOLIDUS (/)
not-newline   = %x0000-0009 / %x000B-10FFFF
                ; a scalar value other than U+000A LINE FEED (LF)
not-star      = %x0000-0029 / %x002B-10FFFF
                ; a scalar value other than U+002A ASTERISK (*)
not-slash     = %x0000-002E / %x0030-10FFFF
                ; a scalar value other than U+002F SOLIDUS (/)

これは、JavaScriptのコメントで要素のコンテンツを設置するものと一致する。

この要求は、script要素のコンテンツの構文上に先の制約に加えて存在する。

以下は、依然として外部スクリプトファイルを参照する間に文書内で、著者がライセンス情報やAPI情報のような文書を含むことを許可する。src属性を提供する一方で、偶然にも著者が有効なスクリプトのように見えるものが含まないように、構文は制約される。

<script src="cool-effects.js">
 // create new instances using:
 //    var e = new Effect();
 // start the effect using .play, stop using .stop:
 //    e.play();
 //    e.stop();
</script>
4.12.1.5 Interaction of script elements and XSLT

この節は非規範的である。

This specification does not define how XSLT interacts with the script element. However, in the absence of another specification actually defining this, here are some guidelines for implementers, based on existing implementations:

The main distinction between the first two cases and the last case is that the first two operate on Documents and the last operates on a fragment.

4.12.2 noscript要素

Element/noscript

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
カテゴリー
メタデータコンテンツ
フローコンテンツ
フレージングコンテンツ
この要素を使用できるコンテキスト
先祖noscript要素が存在しない場合、HTML文書head要素内。
先祖noscript要素が存在しない場合、HTML文書フレージングコンテンツが期待される場所。
コンテンツモデル
スクリプトが無効の場合、head要素内で:任意の順で、0個以上のlink要素、0個以上のstyle要素、0個以上のmeta要素。
スクリプトが無効の場合、head要素外で:透過的。ただし、noscript要素の子孫を持ってはならない。
そうでなければ:文で与えられる要件に適合するテキスト。
text/htmlにおけるタグ省略
どちらのタグも省略不可。
コンテンツ属性
グローバル属性
アクセシビリティの考慮
著者向け
実装者向け
DOMインターフェイス
HTMLElementを使用する。

noscript要素は、スクリプトが有効である場合は何も表さず、スクリプトが無効である場合は要素の子を表す。これは、文書が解析される方法に影響を与えることによって、スクリプトをサポートするユーザーエージェントとサポートしないユーザーエージェントに異なるマークアップを提示するために使用される。

HTML文書で使用する場合、許可されるコンテンツモデルは次のとおり:

スクリプトが無効である場合、head要素内のnoscript要素に対して

noscript要素は、linkstyle、およびmeta要素のみを含まなければならない。

スクリプトが有効である場合、head要素内のnoscript要素に対して

noscript要素は、テキストのみを含まなければならない。ただし、context要素としてnoscript要素をもつHTML断片解析アルゴリズムを呼び出し、かつinputとしてテキストコンテンツを呼び出すと、noscript要素の子であった場合に適合するだろう、linkstylemeta要素のみからなるノードのリストをもたらさなければならず、かつ解析エラーでない場合を除く。

スクリプトが無効である場合、head要素外のnoscript要素に対して

noscript要素のコンテンツモデルは透過的であり、同時にnoscript要素がnoscript要素を持ってはならない(noscript要素を入れ子にできない)追加制限がある。

スクリプトが有効である場合、head要素外のnoscript要素に対して

noscript要素はテキストのみを含まなければならない。ただしテキストは、以下のアルゴリズムがnoscript要素およびscript要素をもたない適合文書をもたらすものでなければならず、アルゴリズムでステップは例外を投げるまたはHTMLパーサー解析エラーを起こさないようにしなければならない:

  1. 文書からすべてのscript要素を取り除く。
  2. 文書においてすべてのnoscript要素のリストを作る。そのリストの各noscript要素に対して、以下のステップを実行する:
    1. snoscript要素要素の子テキストコンテンツとする。
    2. noscript要素のouterHTML属性をsの値に設定する。(これは、副作用としてnoscript要素を文書から除去させる。)[DOMPARSING]

歴史的な理由により、パーサーが呼び出されたときにスクリプトが有効にされたかどうかに基づくHTMLパーサーによってnoscript要素が異なる方法で処理されるので、これらのすべてのこじつけが必要とされる。

noscriptXML文書で使用してはならない。

noscript要素はHTML構文でのみ有効だが、XML構文では効果がない。スクリプトが有効である場合、この要素が動作する方法は、基本的にパーサーを"オフ"にすることであり、要素の内容は、実際の要素としてではなく純粋にテキストとして扱われているのである。XMLは、これを実行するためのメカニズムを定義しない。

The noscript element has no other requirements. In particular, children of the noscript element are not exempt from form submission, scripting, and so forth, even when scripting is enabled for the element.

次の例において、noscript要素は、スクリプトのフォールバックを提供するために使用される。

<form action="calcSquare.php">
 <p>
  <label for=x>Number</label>:
  <input id="x" name="x" type="number">
 </p>
 <script>
  var x = document.getElementById('x');
  var output = document.createElement('p');
  output.textContent = 'Type a number; it will be squared right then!';
  x.form.appendChild(output);
  x.form.onsubmit = function () { return false; }
  x.oninput = function () {
    var v = x.valueAsNumber;
    output.textContent = v + ' squared is ' + v * v;
  };
 </script>
 <noscript>
  <input type=submit value="Calculate Square">
 </noscript>
</form>

スクリプトが無効である場合、ボタンは、サーバー側で計算を行うために表示される。スクリプトが有効である場合、代わりに値がその場で計算される。

noscript要素は鈍器である。時には、スクリプトを有効にするかもしれないが、何らかの理由でページのスクリプトが失敗するかもしれない。このような理由から、次の例のように、noscript要素の使用を避ける代わりに、その場でスクリプトのないページからスクリプト化されたページにページを変更するスクリプトを設計することが一般により良い:

<form action="calcSquare.php">
 <p>
  <label for=x>Number</label>:
  <input id="x" name="x" type="number">
 </p>
 <input id="submit" type=submit value="Calculate Square">
 <script>
  var x = document.getElementById('x');
  var output = document.createElement('p');
  output.textContent = 'Type a number; it will be squared right then!';
  x.form.appendChild(output);
  x.form.onsubmit = function () { return false; }
  x.oninput = function () {
    var v = x.valueAsNumber;
    output.textContent = v + ' squared is ' + v * v;
  };
  var submit = document.getElementById('submit');
  submit.parentNode.removeChild(submit);
 </script>
</form>

上記の手法は、noscriptが許可されていないため、XML文書でも役に立つ。

4.12.3 template要素

Element/template

Support in all current engines.

Firefox22+Safari8+Chrome26+
Opera?Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView AndroidYesSamsung Internet?Opera Android?

HTMLTemplateElement

Support in all current engines.

Firefox22+Safari8+Chrome26+
Opera?Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
カテゴリー
メタデータコンテンツ
フローコンテンツ
フレージングコンテンツ
スクリプトサポート要素
この要素を使用できるコンテキスト
メタデータコンテンツが期待される場所。
フレージングコンテンツが期待される場所。
スクリプトサポート要素が期待される場所。
span属性を持たないcolgroup要素の子として。
コンテンツモデル
Nothing(明確化のために、例を参照)。
text/htmlにおけるタグ省略
どちらのタグも省略不可。
コンテンツ属性
グローバル属性
shadowrootmode — Enables streaming declarative shadow roots
shadowrootdelegatesfocus — Sets delegates focus on a declarative shadow root
shadowrootclonable — Sets clonable on a declarative shadow root
shadowrootserializable — Sets serializable on a declarative shadow root
アクセシビリティの考慮
著者向け
実装者向け
DOMインターフェイス
[Exposed=Window]
interface HTMLTemplateElement : HTMLElement {
  [HTMLConstructor] constructor();

  readonly attribute DocumentFragment content;
  [CEReactions] attribute DOMString shadowRootMode;
  [CEReactions] attribute boolean shadowRootDelegatesFocus;
  [CEReactions] attribute boolean shadowRootClonable;
  [CEReactions] attribute boolean shadowRootSerializable;
};

template要素は、複製され、スクリプトによって文書に挿入できるHTMLの断片を宣言するために使用される。

レンダリングにおいて、template要素は何も表さない。

The shadowrootmode content attribute is an enumerated attribute with the following keywords and states:

キーワード状態概要
openopenThe template element represents an open declarative shadow root.
closedclosedThe template element represents a closed declarative shadow root.

The shadowrootmode attribute's invalid value default and missing value default are both the none state.

The shadowrootdelegatesfocus content attribute is a boolean attribute.

The shadowrootclonable content attribute is a boolean attribute.

The shadowrootserializable content attribute is a boolean attribute.

template要素のテンプレートコンテンツは、要素自体の子ではない

DOM操作の結果として、template要素がTextノードと要素ノードを含むことも可能である。しかし、この要素のコンテンツモデルはnothingとして定義されるため、すべてのものはtemplate要素のコンテンツモデルに違反する。

たとえば、次の文書を考えてみる:

<!doctype html>
<html lang="en">
 <head>
  <title>Homework</title>
 <body>
  <template id="template"><p>Smile!</p></template>
  <script>
   let num = 3;
   const fragment = document.getElementById('template').content.cloneNode(true);
   while (num-- > 1) {
     fragment.firstChild.before(fragment.firstChild.cloneNode(true));
     fragment.firstChild.textContent += fragment.lastChild.textContent;
   }
   document.body.appendChild(fragment);
  </script>
</html>

templateにおけるp要素は、DOM内のtemplateの子ではないtemplate要素のcontent IDL属性によって返されるDocumentFragmentの子である。

スクリプトがtemplate要素のappendChild()を呼び出すと、(他の要素の場合と同様に)template要素に子要素が追加される。しかし、そのようにすることは、template要素のコンテンツモデルに違反することになる。

template.content

HTMLTemplateElement/content

Support in all current engines.

Firefox22+Safari8+Chrome26+
Opera?Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

テンプレートコンテンツDocumentFragment)を返す。

Each template element has an associated DocumentFragment object that is its template contents. The template contents have no conformance requirements. When a template element is created, the user agent must run the following steps to establish the template contents:

  1. Let doc be the template element's node document's appropriate template contents owner document.

  2. Create a DocumentFragment object whose node document is doc and host is the template element.

  3. Set the template element's template contents to the newly created DocumentFragment object.

A Document doc's appropriate template contents owner document is the Document returned by the following algorithm:

  1. If doc is not a Document created by this algorithm, then:

    1. If doc does not yet have an associated inert template document, then:

      1. Let new doc be a new Document (whose browsing context is null). This is "a Document created by this algorithm" for the purposes of the step above.

      2. If doc is an HTML document, mark new doc as an HTML document also.

      3. Let doc's associated inert template document be new doc.

    2. Set doc to doc's associated inert template document.

    Each Document not created by this algorithm thus gets a single Document to act as its proxy for owning the template contents of all its template elements, so that they aren't in a browsing context and thus remain inert (e.g. scripts do not run). Meanwhile, template elements inside Document objects that are created by this algorithm just reuse the same Document owner for their contents.

  2. Return doc.

The adopting steps (with node and oldDocument as parameters) for template elements are the following:

  1. Let doc be node's node document's appropriate template contents owner document.

    node's node document is the Document object that node was just adopted into.

  2. Adopt node's template contents (a DocumentFragment object) into doc.

The content getter steps are to return template's template contents, if the template contents is not a ShadowRoot node; otherwise null.

The shadowRootMode IDL attribute must reflect the shadowrootmode content attribute, limited to only known values.

The shadowRootDelegatesFocus IDL attribute must reflect the shadowrootdelegatesfocus content attribute.

The shadowRootClonable IDL attribute must reflect the shadowrootclonable content attribute.

The shadowRootSerializable IDL attribute must reflect the shadowrootserializable content attribute.


The cloning steps for a template element node being cloned to a copy copy must run the following steps:

  1. If the clone children flag is not set in the calling clone algorithm, return.

  2. Let copied contents be the result of cloning all the children of node's template contents, with document set to copy's template contents's node document, and with the clone children flag set.

  3. Append copied contents to copy's template contents.

この例において、スクリプトは、手動でマークアップから構造を生成する代わりに要素構造を提供するためにtemplateを使用して、データ構造からデータをもつテーブル4列に投入する。

<!DOCTYPE html>
<html lang='en'>
<title>Cat data</title>
<script>
 // Data is hard-coded here, but could come from the server
 var data = [
   { name: 'Pillar', color: 'Ticked Tabby', sex: 'Female (neutered)', legs: 3 },
   { name: 'Hedral', color: 'Tuxedo', sex: 'Male (neutered)', legs: 4 },
 ];
</script>
<table>
 <thead>
  <tr>
   <th>Name <th>Color <th>Sex <th>Legs
 <tbody>
  <template id="row">
   <tr><td><td><td><td>
  </template>
</table>
<script>
 var template = document.querySelector('#row');
 for (var i = 0; i < data.length; i += 1) {
   var cat = data[i];
   var clone = template.content.cloneNode(true);
   var cells = clone.querySelectorAll('td');
   cells[0].textContent = cat.name;
   cells[1].textContent = cat.color;
   cells[2].textContent = cat.sex;
   cells[3].textContent = cat.legs;
   template.parentNode.appendChild(clone);
 }
</script>

この例は、templateのコンテンツにcloneNode()を使用する。それは、同じことをするdocument.importNode()を等価的に使用することもできる。ノード文書が更新されるときに、この2つのAPIの唯一の違いがある。ノードがappendChild()で付加される場合にcloneNode()とともに更新され、ノードがクローン化されるときに、document.importNode()とともに更新される。

4.12.3.1 Interaction of template elements with XSLT and XPath

この節は非規範的である。

This specification does not define how XSLT and XPath interact with the template element. However, in the absence of another specification actually defining this, here are some guidelines for implementers, which are intended to be consistent with other processing described in this specification:

4.12.4 slot要素

Element/slot

Support in all current engines.

Firefox63+Safari10+Chrome53+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

HTMLSlotElement

Support in all current engines.

Firefox63+Safari10+Chrome53+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
カテゴリー
フローコンテンツ
フレージングコンテンツ
この要素を使用できるコンテキスト
フレージングコンテンツが期待される場所。
コンテンツモデル
透過的
text/htmlにおけるタグ省略
どちらのタグも省略不可。
コンテンツ属性
グローバル属性
name — シャドウツリースロットの名前
アクセシビリティの考慮
著者向け
実装者向け
DOMインターフェイス
[Exposed=Window]
interface HTMLSlotElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString name;
  sequence<Node> assignedNodes(optional AssignedNodesOptions options = {});
  sequence<Element> assignedElements(optional AssignedNodesOptions options = {});
  undefined assign((Element or Text)... nodes);
};

dictionary AssignedNodesOptions {
  boolean flatten = false;
};

slot要素は、スロットを定義する。典型的にシャドウツリーに使用される。もしあれば、slot要素はその割り当てられるノード表し、そうでなければそのコンテンツを表す。

nameコンテンツ属性は、任意の文字列値を含んでもよい。これはスロット名前を表す。

slot属性は、別の要素にスロットを割り当てるために使用される:name属性をもつslot要素は、その要素がそのname属性の値と一致する値を持つslot属性を持ち、かつslot要素がその対応するslot属性値を持つルートホストを持つシャドウツリーの子である場合、任意の要素が割り当てられる名前付きスロットを作成する。

slot.name

HTMLSlotElement/name

Support in all current engines.

Firefox63+Safari10+Chrome53+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
slot名前を取得し設定することが可能である。
slot.assignedNodes()

HTMLSlotElement/assignedNodes

Support in all current engines.

Firefox63+Safari10+Chrome53+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
slot割り当てられるノードを返す。
slot.assignedNodes({ flatten: true })
もしあれば、slot割り当てられるノードを返し、そうでなければslotの子を返し、かつslot要素が存在しなくなるまで、再帰的に、slot要素に遭遇するのと同じものを返す。
slot.assignedElements()

HTMLSlotElement/assignedElements

Support in all current engines.

Firefox66+Safari12.1+Chrome65+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?
要素に限定された、slot割り当てられたノードを返す。
slot.assignedElements({ flatten: true })
要素に限定されたassignedNodes({ flatten: true })と同じものを返す。
slot.assign(...nodes)

slot手動で割り当てられたノードを、指定されたnodesに設定する。

name IDL属性は、同じ名前のコンテンツ属性を反映しなければならない。

slot要素は、manually assigned nodesを持ち、これは、 assign()によって設定されたslottables順序付きセットである。このセットは、最初は空である。

manually assigned nodesセットは、スクリプトから直接アクセスできないため、slottablesへの弱い参照を使用して実装することができる。

The assignedNodes(options) method steps are:

  1. If options["flatten"] is false, then return this's assigned nodes.

  2. Return the result of finding flattened slottables with this.

The assignedElements(options) method steps are:

  1. If options["flatten"] is false, then return this's assigned nodes, filtered to contain only Element nodes.

  2. Return the result of finding flattened slottables with this, filtered to contain only Element nodes.

HTMLSlotElement/assign

Support in all current engines.

Firefox92+Safari16.4+Chrome86+
Opera?Edge86+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

The assign(...nodes) method steps are:

  1. For each node of this's manually assigned nodes, set node's manual slot assignment to null.

  2. Let nodesSet be a new ordered set.

  3. For each node of nodes:

    1. If node's manual slot assignment refers to a slot, then remove node from that slot's manually assigned nodes.

    2. Set node's manual slot assignment to this.

    3. Append node to nodesSet.

  4. Set this's manually assigned nodes to nodesSet.

  5. Run assign slottables for a tree for this's root.