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におけるタグ省略
どちらのタグも省略䞍可。
コンテンツ属性
グロヌバル属性
type — スクリプトの皮類
src — リ゜ヌスのアドレス
nomodule — モゞュヌルスクリプトをサポヌトするナヌザヌ゚ヌゞェントにおける実行を防ぐ
async — フェッチの間ブロックなしで、可胜な堎合にスクリプトを実行する
defer — スクリプトの実行を延期する
blocking — 芁玠が朜圚的にレンダリングブロッキングであるかどうか
crossorigin — 芁玠が生成元をたたいだ芁求を凊理する方法
referrerpolicy — 芁玠によっお開始されたフェッチのためのリファラヌポリシヌ
integrity — Subresource Integrityチェックで䜿甚される敎合性メタデヌタ[SRI]
fetchpriority — 芁玠によっお開始されるフェッチの優先床を蚭定する
アクセシビリティの考慮
著者向け。
実装者向け。
サニタむれヌション
安党でない。
DOMむンタヌフェむス
[Exposed=Window]
interface HTMLScriptElement : HTMLElement {
  [HTMLConstructor] constructor();

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

  [CEReactions] attribute DOMString text;

  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?

script芁玠には、2぀のコア属性がある。type属性は、衚されるスクリプトの型のカスタマむズを可胜にする

2぀目のコア属性はsrc属性です。これは、クラシックスクリプトおよびJavaScriptモゞュヌルスクリプトに察しおのみ指定しなければならず、芁玠の子テキストコンテンツをスクリプトコンテンツずしお䜿甚する代わりに、指定されたURLからスクリプトがフェッチされるこずを瀺す。srcが指定される堎合、朜圚的にスペヌスで囲たれる劥圓な空でないURLでなければならない。

指定されたscript芁玠に指定できるその他の属性は、次の衚によっお決たる

nomoduleasyncdeferblockingcrossoriginreferrerpolicyintegrityfetchpriority
External classic scriptsYesYesYesYesYesYesYesYes
Inline classic scriptsYes···Yes*Yes*··†
External module scripts·Yes·YesYesYesYesYes
Inline module scripts·Yes··Yes*Yes*··†
Import maps········
Speculation rules········
Data blocks········

* むンラむンスクリプトには初期フェッチがないが、むンラむンスクリプトのcrossoriginおよびreferrerpolicy属性は、動的import()を含むモゞュヌルむンポヌトで䜿甚されるcredentials modeおよびreferrerpolicyに圱響する。

† crossoriginおよびreferrerpolicyずは異なり、fetchpriorityはモゞュヌルのむンポヌトに圱響しない。See some discussion in issue #10276.


むンラむンscript芁玠、たたは倖郚スクリプトリ゜ヌスのコンテンツは、それぞれクラシックスクリプトおよびJavaScriptモゞュヌルスクリプトに察するJavaScript仕様のScriptたたはModule生成物の芁件に適合しなければならない。[JAVASCRIPT]

むンポヌトマップのむンラむンscript芁玠のコンテンツは、むンポヌトマップのオヌサリング芁件に適合しなければならない。

投機ルヌルセットのむンラむンscript芁玠のコンテンツは、投機ルヌルセットのオヌサリング芁件に適合しなければならない。

デヌタブロックを含めるために䜿甚される堎合、デヌタは、むンラむンに埋め蟌たれなければならず、デヌタの圢匏は、type属性を䜿甚しお指定しなければならず、か぀script芁玠のコンテンツは、䜿甚される圢匏のために定矩される芁件に適合しなければならない。


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属性は、どのようにスクリプトが評䟡されるべきかを瀺す真停属性である。スクリプトのタむプに応じお、これらの属性を䜿甚しお遞択できる耇数の可胜なモヌドが存圚する。

倖郚のクラシックスクリプトでは、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の偎面を含む。したがっお、実装芁求は必然的に仕様のあらゆる堎所に散圚しおいる。The algorithms below describe the core of this processing, but these algorithms reference and are referenced by the parsing rules for script start and end tags in HTML, in foreign content, and in XML, the rules for the document.write() method, the handling of scripting, etc.

document.write()メ゜ッドを䜿甚しお挿入するずき、通垞はscript芁玠が実行される䞀般に、スクリプトの実行たたはHTMLの解析をブロックする。innerHTML属性ずouterHTML属性を䜿甚しお挿入する堎合、それらは䞀切実行されない。

たずえasync属性が指定されおも、デフォルトずなるブロッキング動䜜の代わりにdeferの動䜜をフォヌルバックするために、deferのみをサポヌトするか぀asyncをサポヌトしないレガシヌりェブブラりザヌをもたらすため、defer属性は指定されおもよい。

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

crossorigin属性はCORS蚭定属性である。倖郚クラシックスクリプトの堎合、スクリプトが他の生成元から取埗されたずき、゚ラヌ情報を衚瀺するかどうかを制埡する。倖郚モゞュヌルスクリプトの堎合、異なる生成元であれば、モゞュヌル゜ヌスの初期フェッチに䜿甚される資栌モヌドを制埡する。クラシックずモゞュヌルスクリプトずの䞡方で、異なる生成元のモゞュヌルのむンポヌトに䜿甚される資栌情報モヌドを制埡する。

クラシックスクリプトずは異なり、モゞュヌルスクリプトは、生成元をたたいだフェッチのためにCORSプロトコルを䜿甚する必芁がある。

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>

integrity属性は、倖郚スクリプトの初期フェッチに䜿甚される完党性メタデヌタを蚭定する。その倀はintegrity属性の芁件にマッチしなければならない。[SRI]

fetchpriorityは、フェッチ優先床属性である。倖郚スクリプトの初期フェッチに䜿甚される優先順䜍を蚭定する。

Changing any of these attributes dynamically has no direct effect; these attributes are only used at specific times described in the processing model.


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

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 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 ]

芁玠の子テキストコンテンツを返す。

script.text = value

芁玠の子をvalueで指定されたテキストに眮き換える。

HTMLScriptElement.supports(type)

指定されたtypeがナヌザヌ゚ヌゞェントによっおサポヌトされるスクリプトタむプである堎合、trueを返す。この仕様で可胜なスクリプトタむプは"classic"、"module"および"importmap"であるが、将来的に他のタむプが远加される可胜性がある。

The text getter steps are to return this's child text content.

The text setter steps are to string replace all with the given value within this.

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?

The static supports(type) method steps are:

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

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

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

  4. If type is "speculationrules", then return true.

  5. falseを返す。

type匕数は、これらの倀ず正確に䞀臎する必芁がある。ASCII倧文字・小文字䞍区別䞀臎は実行しない。これは、typeコンテンツ属性倀の凊理方法、およびDOMTokenListのsupports()メ゜ッドの動䜜ずは異なるが、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", "importmap", or "speculationrules", 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, an import map parse result, or a speculation rules 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 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 script elements given node, copy, and subtree are to set copy's already started to node'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.


The script HTML element post-connection steps, given insertedNode, are:

  1. If insertedNode is parser-inserted, then return.

  2. Prepare the script element given insertedNode.

The HTML element post-connection steps only run when the inserted element is still connected, which protects against cases where an earlier-inserted script removes a later-inserted script. For instance:

<script>
const script1 = document.createElement('script');
script1.innerText = `
  document.querySelector('#script2').remove();
`;

const script2 = document.createElement('script');
script2.id = 'script2';
script2.textContent = `console.log('script#2 running')`;

document.body.append(script1, script2);
</script>

Nothing is printed to the console in this example. By the time the HTML element post-connection steps run for the first script that was atomically inserted by append(), it can observe that the second script is already connected to the DOM, and it removes it from the DOM. Because the second script is no longer connected, its HTML element post-connection steps do not run, and it does not get prepared.

The script HTML element removing steps given removedNode are:

  1. If removedNode's result is a speculation rules parse result:

    1. Unregister speculation rules given removedNode's relevant global object and removedNode's result.

    2. Set removedNode's already started to false.

    3. Set removedNode's result to null.

The script children changed steps given changedNode are:

  1. If the script element is not connected, then return.

  2. Run the script HTML element post-connection steps, given changedNode.

This has an interesting implication on the execution order of a script element and any newly-inserted child script elements. 次の断片を考えおみる

<script id=outer-script></script>

<script>
  const outerScript = document.querySelector('#outer-script');

  const start = new Text('console.log(1);');
  const innerScript = document.createElement('script');
  innerScript.textContent = `console.log('inner script executing')`;
  const end = new Text('console.log(2);');

  outerScript.append(start, innerScript, end);

  // Logs:
  // 1
  // 2
  // inner script executing
</script>

By the time the second script block executes, the outer-script has already been prepared, but because it is empty, it did not execute and therefore is not marked as already started. The atomic insertion of the Text nodes and nested script element have the following effects:

  1. All three child nodes get atomically inserted as children of outer-script; all of their insertion steps run, which have no observable consequences in this case.

  2. The outer-script's children changed steps run, which prepares that script; because its body is now non-empty, this executes the contents of the two Text nodes, in order.

  3. The script HTML element post-connection steps finally run for innerScript, causing its body to execute.

The following attribute change steps, given element, localName, oldValue, value, and namespace, are used for all script elements:

  1. If namespace is not null, then return.

  2. If localName is src, value is not null, and element is connected, then run the script HTML element post-connection steps, given element.

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:

    • el has a type attribute whose value is the empty string;

    • el has no type attribute but it has a language attribute and that attribute's value is the empty string; or

    • el has neither a type attribute nor a language attribute,

    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, if the script block's type string is an ASCII case-insensitive match for the string "speculationrules", then set el's type to "speculationrules".

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

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

  15. Set el's already started to true.

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

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

  18. 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]

  19. 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.

  20. Let cspType be "script speculationrules" if el's type is "speculationrules"; otherwise, "script".

  21. 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, cspType, and source text, then return. [CSP]

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

    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.

  23. 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.

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

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

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

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

    Otherwise, let integrity metadata be the empty string.

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

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

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

  31. 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.

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

  33. If el has a src content attribute:

    1. If el's type is "importmap" or "speculationrules", 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 maps and speculation rules are not currently supported. See WICG/import-maps issue #235 and WICG/nav-speculation issue #348 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"

      If el does not have an integrity attribute, then set options's integrity metadata to the result of resolving a module integrity metadata with url and settings object.

      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.

  34. 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:

        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. Queue an element task on the networking task source given el to perform the following steps:

          1. Mark as ready el given result.

          Queueing a task here means that, even if the inline module script has no dependencies or synchronously results in a parse error, we won't proceed to execute the script element synchronously.

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

      2. Mark as ready el given result.

      "speculationrules"
      1. Let result be the result of creating a speculation rules parse result given source text and el's node document.

      2. Mark as ready el given result.

  35. 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.)

  36. 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.

    "speculationrules"
    1. Register speculation rules 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倧文字・小文字䞍区別の䞀臎で"<!--"を"<\!--"に、"<script"を"<\script"に、および"</script"を"<\/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

Avoid using client-side XSLT in browsers. The browser implementations of XSLT are highly susceptible to memory safety vulnerabilities, and the web platform has evolved toward JavaScript as the safe replacement. For these reasons, this feature is in the process of being removed from the web platform. これは䜕幎もかかる長いプロセスである。

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

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文曞でフレヌゞングコンテンツが期埅される堎所。
先祖noscript芁玠がない堎合、select芁玠たたはoptgroup芁玠の子孫ずしお。
コンテンツモデル
スクリプトが無効の堎合、head芁玠内で任意の順で、0個以䞊のlink芁玠、0個以䞊のstyle芁玠、0個以䞊のmeta芁玠。
スクリプトが無効の堎合、head芁玠倖で透過的。ただし、noscript芁玠の子孫を持っおはならない。
そうでなければ文で䞎えられる芁件に適合するテキスト。
text/htmlにおけるタグ省略
どちらのタグも省略䞍可。
コンテンツ属性
グロヌバル属性
アクセシビリティの考慮
著者向け。
実装者向け。
サニタむれヌション
未分類。
DOMむンタヌフェむス
HTMLElementを䜿甚する。

noscript芁玠は、スクリプトが有効である堎合は䜕も衚さず、スクリプトが無効である堎合は芁玠の子を衚す。これは、文曞が解析される方法に圱響を䞎えるこずによっお、スクリプトをサポヌトするナヌザヌ゚ヌゞェントずサポヌトしないナヌザヌ゚ヌゞェントに異なるマヌクアップを提瀺するために䜿甚される。

HTML文曞で䜿甚する堎合、蚱可されるコンテンツモデルは次のずおり

スクリプトが無効である堎合、head芁玠内のnoscript芁玠に察しお

noscript芁玠は、link、style、およびmeta芁玠のみを含たなければならない。

スクリプトが有効である堎合、head芁玠内のnoscript芁玠に察しお

noscript芁玠は、テキストのみを含たなければならない。ただし、context芁玠ずしおnoscript芁玠をも぀HTML断片解析アルゎリズムを呌び出し、か぀inputずしおテキストコンテンツを呌び出すず、noscript芁玠の子であった堎合に適合するだろう、link、style、meta芁玠のみからなるノヌドのリストをもたらさなければならず、か぀解析゚ラヌでない堎合を陀く。

スクリプトが無効である堎合、head芁玠倖のnoscript芁玠に察しお

noscript芁玠のコンテンツモデルは透過的であり、同時にnoscript芁玠がnoscript芁玠を持っおはならないnoscript芁玠を入れ子にできない远加制限がある。

スクリプトが有効である堎合、head芁玠倖のnoscript芁玠に察しお

noscript芁玠はテキストのみを含たなければならない。ただしテキストは、次のアルゎリズムがnoscript芁玠およびscript芁玠をもたない適合文曞をもたらすものでなければならず、アルゎリズムでステップは䟋倖を投げるたたはHTMLパヌサヌに解析゚ラヌを起こさないようにしなければならない

  1. 文曞からすべおのscript芁玠を取り陀く。
  2. 文曞においおすべおのnoscript芁玠のリストを䜜る。そのリストの各noscript芁玠に察しお、次のステップを実行する
    1. sをnoscript芁玠芁玠の子テキストコンテンツずする。
    2. noscript芁玠のouterHTML属性をsの倀に蚭定する。これは、副䜜甚ずしおnoscript芁玠を文曞から陀去させる。

歎史的な理由により、パヌサヌが呌び出されたずきにスクリプトモヌドが無効かどうかに基づくHTMLパヌサヌによっおnoscript芁玠が異なる方法で凊理されるので、これらのすべおのこじ぀けが必芁ずされる。

noscriptはXML文曞で䜿甚しおはならない。

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におけるタグ省略
どちらのタグも省略䞍可。
コンテンツ属性
グロヌバル属性
for — 既存のコンテンツを曎新する
shadowrootmode — 宣蚀的なシャドりルヌトのストリヌミングを有効にする
shadowrootdelegatesfocus — 宣蚀的なシャドりルヌトに代理フォヌカスを蚭定する
shadowrootserializable — 宣蚀的なシャドりルヌトにシリアラむズ可胜を蚭定する
shadowrootslotassignment — 宣蚀的なシャドりルヌトにスロット割り圓おを蚭定する
shadowrootclonable — 宣蚀的なシャドりルヌトにクロヌン可胜を蚭定する
shadowrootcustomelementregistry — 宣蚀的なシャドりルヌトを有効にしお、カスタム芁玠レゞストリを䜿甚するこずを瀺す
アクセシビリティの考慮
著者向け。
実装者向け。
サニタむれヌション
未分類。
DOMむンタヌフェむス
[Exposed=Window]
interface HTMLTemplateElement : HTMLElement {
  [HTMLConstructor] constructor();

  readonly attribute DocumentFragment content;
  [CEReactions, Reflect="for"] attribute DOMString htmlFor;
  [CEReactions] attribute DOMString shadowRootMode;
  [CEReactions, Reflect] attribute boolean shadowRootDelegatesFocus;
  [CEReactions, Reflect] attribute boolean shadowRootSerializable;
  [CEReactions] attribute DOMString shadowRootSlotAssignment;
  [CEReactions, Reflect] attribute boolean shadowRootClonable;
  [CEReactions, Reflect] attribute DOMString shadowRootCustomElementRegistry;
};

template芁玠は、耇補され、スクリプトによっお文曞に挿入できるHTMLの断片を宣蚀するために䜿甚される。

レンダリングにおいお、template芁玠は䜕も衚さない。

forコンテンツ属性は、コンテンツを挿入する䜍眮<?marker>、たたは眮き換える範囲の開始䜍眮<?start>を瀺すProcessingInstructionを識別する。この属性が指定されおいる堎合、この属性の倀は、template芁玠ず同じツリヌ内にある<?marker>たたは<?start> ProcessingInstructionのname属性の倀ず同じでなければならない。

shadowrootmodeコンテンツ属性は、次のキヌワヌドおよび状態をも぀列挙属性である

キヌワヌド状態抂芁
openOpentemplate芁玠は、開いた宣蚀的なシャドりルヌトを衚す。
closedClosedtemplate芁玠は、閉じた宣蚀的なシャドりルヌトを衚す。

shadowrootmode属性の無効倀のデフォルトおよび欠損倀のデフォルトは、䞡方ずもnone状態である。

shadowrootdelegatesfocusコンテンツ属性は、真停属性である。

shadowrootserializableコンテンツ属性は、真停属性である。

shadowrootslotassignmentコンテンツ属性は、次のキヌワヌドおよび状態をも぀列挙属性である

キヌワヌド状態抂芁
namedNamed宣蚀型シャドりルヌトは、名前付きスロット割り圓おを䜿甚する。
manualManual宣蚀的なシャドりルヌトは、手動のスロット割り圓おを䜿甚する。

shadowrootslotassignment属性の䞍正倀のデフォルトず欠損倀のデフォルトの䞡方は、Named状態である。

shadowrootclonableコンテンツ属性は、真停属性である。

shadowrootcustomelementregistryコンテンツ属性は、真停属性である。

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 document be the template element's node document's appropriate template contents owner document.

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

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

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

  1. If document is not a Document created by this algorithm:

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

      1. Let newDocument be the result of creating a document that implements Document, given document's relevant realm; its browsing context is null. This is "a Document created by this algorithm" for the purposes of the step above.

      2. If document is an HTML document, then mark newDocument as an HTML document also.

      3. Set document's associated inert template document to newDocument.

    2. Set document to document'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 document.

Each template element has an associated Element-or-DocumentFragment-or-null insertion target, which is initially null.

Each template element has an associated ProcessingInstruction-or-null insertion start marker and insertion end marker, which are initially null.

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

  1. Let document 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 document.

The content getter steps are:

  1. Assert: this's template contents is not a ShadowRoot node.

  2. Return this's template contents.

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

The shadowRootSlotAssignment IDL attribute must reflect the shadowrootslotassignment content attribute, limited to only known values.

The shadowRootCustomElementRegistry IDL attribute intentionally does not have a boolean type so it can be extended.


The cloning steps for template elements given node, copy, and subtree are:

  1. If subtree is false, then return.

  2. For each child of node's template contents's children, in tree order: clone a node given child with document set to copy's template contents's node document, subtree set to true, and parent set to copy's template contents.

To prepare content patching given an Element or DocumentFragment scope and a template element template:

  1. Assert: template's for attribute is specified.

  2. Let markerName be template's for attribute's value.

  3. If markerName is the empty string, then return false.

  4. Let (start, end) be the result of find markers given scope and markerName.

  5. If start is null, then return false.

  6. Set template's insertion target to start's parent.

  7. Set template's insertion start marker to start.

  8. Set template's insertion end marker to end.

  9. If start is end, then return true.

  10. Let removedNodes be an empty list.

  11. Let currentNode be start's next sibling.

  12. While currentNode is not null:

    1. If currentNode is end, then break.

    2. Append currentNode to removedNodes.

    3. Set currentNode to currentNode's next sibling.

  13. For each node of removedNodes:

    1. If node's parent is not null, then remove node.

      The parent might have changed because removing a node can fire events like the pagehide event, and an event handler can mutate the DOM. The parent identity is not checked; as long as the node still has a parent, it is removed.

  14. Return true.

To find markers given a node scope and a string name:

  1. For each descendant of scope's descendants, in tree order:

    1. If descendant is not a ProcessingInstruction node, then continue.

    2. If the result of getting a processing instruction attribute given descendant and "name" is not name, then continue.

    3. If descendant's target is "marker", then return (descendant, descendant).

    4. If descendant's target is "start":

      1. Let start be descendant.

      2. Let nestingLevel be 0.

      3. Let sibling be start's next sibling.

      4. While sibling is not null:

        1. If sibling is a ProcessingInstruction node:

          1. If sibling's target is "start", then increment nestingLevel by one.

          2. If sibling's target is "end":

            1. If nestingLevel is 0, then return (start, sibling).

            2. Decrement nestingLevel by one.

        2. Set sibling to sibling's next sibling.

      5. Return (start, null).

        No matching <?end> was found, which is interpreted as a range from start to the end of its parent.

  2. Return (null, null).

この䟋においお、スクリプトは、手動でマヌクアップから構造を生成する代わりに芁玠構造を提䟛するために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()ずずもに曎新される。

この䟋では、ペヌゞのメむンコンテンツが配信された埌、for属性をも぀template芁玠を䜿甚しおselect芁玠に囜のリストを取り蟌む。

<!DOCTYPE html>
<html lang="en">
 <head>
  <title>Out-of-order countries</title>
  <style>
   #countries:empty {
    opacity: 0;
   }
  </style>
 </head>
 <body>
  <select id=countries><?marker name="country-options"?></select>
  ...
  <template for="country-options"><option>Antigua</option>...</template>
 </body>
</html>

<?marker?>凊理呜什は、埌のtemplate芁玠のoption芁玠に眮き換えられる。select芁玠は、倀が蚭定されるたで透過的である。

この䟋では、for属性をも぀template芁玠が䜿甚されおおり、文曞を順䞍同でストリヌミングするために、たず高速な静的コンテンツを送り、そしおサヌバヌ䞊で非同期的に利甚可胜になった時点で蚈算された掚奚情報を送信しおいる。

<!DOCTYPE html>
<html lang="en">
 <head>
  <title>Async recommendation engine</title>
  <style>
   aside {
    /* position the aside where it can grow without causing layout shift or obscuring other content */
   }
   aside:has(.placeholder) {
    /* style the placeholder content */
   }
  </style>
 </head>
 <body>
  <h1>How to train your cat</h1>
  <p>Set realistic goals and don't expect your cat to make a perfect cup of tea
  on the first try.</p>
  <aside>
    <p>Recommended reading:</p>
    <?start name="recommended">
    <ul class="placeholder">
      <li>...</li>
      <li>...</li>
      <li>...</li>
    </ul>
    <?end>
  </aside>
  <p>...</p>
  <p>Now sit back and enjoy your tea with your cat.</p>

  <!-- The server has a potentially long delay at this point. -->

  <template for="recommended">
    <ul>
      <li>Cat or butler, which is right for you?</li>
      <li>Rewarding good cat behavior</li>
      <li>Kettles considered harmful</li>
    </ul>
  </template>
 </body>
</html>

<?start name="recommended">ず<?end>ずの間のコンテンツは、 templateのコンテンツに眮き換えられる。新しいコンテンツはclass="placeholder"を䜿甚しないため、プレヌスホルダヌのスタむルは適甚されなくなる。

4.12.3.1 Interaction of template elements with XSLT and XPath

Avoid using client-side XSLT in browsers. The browser implementations of XSLT are highly susceptible to memory safety vulnerabilities, and the web platform has evolved toward JavaScript as the safe replacement. For these reasons, this feature is in the process of being removed from the web platform. これは䜕幎もかかる長いプロセスである。

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

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, Reflect] 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に蚭定する。

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.