Living Standard — Last Updated 12 December 2024
スクリプトは著者が文書に双方向性を追加することを許可する。
著者は、宣言型のメカニズムがしばしばより保守しやすく、かつ多くのユーザーがスクリプトを無効としているため、可能であれば、スクリプトに宣言型の代替を使用するよう推奨される。
For example, instead of using a script to show or hide a section to show more details, the details
element could be used.
著者はまた、スクリプトのサポートがない状態でそれらのアプリケーションが行儀よくデグレードするよう推奨される。
たとえば、著者がテーブルヘッダーにおいてリンクに動的なテーブルの再ソートを提供する場合、リンクはまたサーバーからソートされたテーブルを要求することによって、スクリプトなしで機能させることができるかもしれない。
script
elementSupport in all current engines.
Support in all current engines.
src
属性が存在しない場合、type
属性の値に依存するが、スクリプトの内容制限に一致しなければならない。src
属性が存在する場合、要素は空またはスクリプト文書を含むだけでなくスクリプトの内容制限に一致するかのいずれかでなければならない。src
— リソースのアドレスtype
— スクリプトの種類nomodule
— モジュールスクリプトをサポートするユーザーエージェントにおける実行を防ぐasync
— フェッチの間ブロックなしで、可能な場合にスクリプトを実行するdefer
— スクリプトの実行を延期するcrossorigin
— 要素がcrossorigin要求を処理する方法integrity
— Subresource Integrityチェックで使用される整合性メタデータ[SRI]referrerpolicy
— 要素によって開始されたフェッチのためのリファラポリシーblocking
— Whether the element is potentially render-blockingfetchpriority
— Sets the priority for fetches initiated by the element[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
要素は、著者が文書に動的スクリプトおよびデータブロックを含むことを許可する。この要素は、ユーザーにコンテンツを表すものでない。
Support in all current engines.
type
属性は、表されるスクリプトの型をカスタマイズを可能にする:
属性を省略する、空文字列に設定する、またはJavaScript MIMEタイプエッセンスマッチに設定することは、スクリプトがJavaScript Scriptトップレベル制作物によって解釈されるようなクラシックスクリプトであることを意味する。クラシックスクリプトはasync
属性およびdefer
属性の影響を受けるが、src
属性が設定されている場合のみである。著者は重複して設定する代わりに、type
属性を省略すべきである。
Setting the attribute to an ASCII case-insensitive match for "module
" means that the script is a JavaScript module script, to be interpreted according to the JavaScript Module top-level production. モジュールスクリプトはdefer
属性の影響を受けないが、 async
属性の影響を受ける(src
属性の状態に関係なく)。
Setting the attribute to an ASCII case-insensitive match for "importmap
" means that the script is an import map, containing JSON that will be used to control the behavior of module specifier resolution. Import maps can only be inline, i.e., the src
attribute and most other attributes are meaningless and not to be used with them.
他の値に属性を設定することは、スクリプトが処理されないデータブロックであることを意味する。(type
自身を除く)script
属性のいずれもデータブロック上で任意の効果を持たない。著者は、データブロックを示すためにJavaScript MIMEタイプエッセンシャルマッチでない妥当なMIMEタイプ文字列を使用しなければならない。
データブロックが妥当なMIMEタイプ文字列を使用して表記されなければならない要件は、潜在的な将来の衝突を回避するための場所である。この仕様がスクリプトの追加の型をいずれ追加する場合、その追加の型は"module
"値がモジュールスクリプトを表す方法のように、MIMEタイプでない何かにtype
属性を設定することによってトリガーされる。現在に妥当なMIMEタイプ文字列を使用することで、将来のユーザーエージェントでさえも、データブロックが異なるスクリプトタイプとして再解釈されないことを保証する。
Classic scripts and JavaScript module scripts can be embedded inline, or be imported from an external file using the src
attribute, which if specified gives the URL of the external script resource to use. src
が指定される場合、潜在的にスペースで囲まれる妥当な空でないURLでなければならない。
The contents of inline script
elements, or the external script resource, must conform with the requirements of the JavaScript specification's Script or Module productions, for classic scripts and JavaScript module scripts respectively. [JAVASCRIPT]
The contents of the external script resource for CSS module scripts must conform to the requirements of the CSS specification. [CSS]
The contents of the external script resource for JSON module scripts must conform to the requirements of the JSON specification. [JSON]
The contents of inline script
elements for import maps must conform with the import map authoring requirements.
For import map script
elements, the src
, async
, nomodule
, defer
, crossorigin
, integrity
, and referrerpolicy
attributes must not be specified.
A document must not have more than one import map script
element.
データブロックを含めるために使用される場合、データは、インラインに埋め込まれなければならず、データの形式は、type
属性を使用して指定しなければならず、かつscript
要素のコンテンツは、使用される形式のために定義される要件に適合しなければならない。The src
, async
, nomodule
, defer
, crossorigin
, integrity
, referrerpolicy
, and fetchpriority
attributes must not be specified.
nomodule
属性は、モジュールスクリプトをサポートするユーザーエージェントでスクリプトが実行されないようにする真偽属性である。これは、以下に示すように、モダンなユーザーエージェントのモジュールスクリプトと古いユーザーエージェントのクラシックスクリプトの選択的な実行を可能にする。nomodule
属性をモジュールスクリプトで指定してはならない(この属性がある場合は無視される)。
Support in all current engines.
Support in all current engines.
async
およびdefer
属性は、どのようにスクリプトが評価されるべきかを示す真偽属性である。クラシックスクリプトは、defer
またはasync
を指定してもよいが、src
属性が存在しない限り、いずれかを指定してはならない。モジュールスクリプトはasync
属性を指定してもよいが、defer
属性を指定してはならない。
これらの属性を使用して、スクリプトの種類によって選択できる複数の可能なモードが存在する。
クラシックスクリプトについて、async
属性が存在する場合、クラシックスクリプトは、構文解析と並行してフェッチされるとすぐに(潜在的に構文解析が完了する前に)利用可能になると評価される。async
が存在しないがdefer
属性が存在する場合、クラシックスクリプトは、並行してフェッチされ、ページが解析終了した際に評価される。いずれの属性も存在しない場合、スクリプトは、両方が完了するまで解析を阻止して、すぐにフェッチされ評価される。
モジュールスクリプトについて、async
属性が存在する場合、モジュールスクリプトとそのすべての依存関係は、構文解析と並行してフェッチされ、モジュールスクリプトは利用可能になるとすぐに(潜在的に構文解析が完了する前に)評価される。そうでなければ、モジュールスクリプトとその依存関係は、構文解析と並行してフェッチされ、ページが解析終了した際に評価される。(defer
属性は、モジュールスクリプトに影響しない。)
これは、次の模式図にすべて要約される:
これら属性の正確な処理の詳細は、主に歴史的な理由から、いくぶん自明でない、多くのHTMLの側面を含む。したがって、実装要求は必然的に仕様のあらゆる場所に散在している。(この節の)下記のアルゴリズムは、この処理の中核を説明するが、これらのアルゴリズムが参照する、およびHTMLにおけるscript
の開始タグと終了タグに対する構文解析規則、無関係なコンテンツで、XMLで、document.write()
メソッドに対する規則、スクリプトの取り扱いなどによって参照される。
document.write()
メソッドを使用して挿入するとき、通常はscript
要素が実行される(一般に、スクリプトの実行またはHTMLの解析をブロックする)。innerHTML
属性とouterHTML
属性を使用して挿入する場合、それらは一切実行されない。
The defer
attribute may be specified even if the async
attribute is specified, to cause legacy web browsers that only support defer
(and not async
) to fall back to the defer
behavior instead of the blocking behavior that is the default.
crossorigin
属性はCORS設定属性である。クラシックスクリプトについて、スクリプトが他の生成元から得られる場合、エラー情報が公開されるかどうかを制御する。モジュールスクリプトについて、クロスオリジンのリクエストに使用される資格情報モードを制御する。
クラシックスクリプトとは異なり、モジュールスクリプトは、クロスオリジンフェッチのためにCORSプロトコルを使用する必要がある。
integrity
属性は、この要素が責任を負うリクエストに対する完全性メタデータを表す。値はテキストである。The integrity
attribute must not be specified when the src
attribute is not specified. [SRI]
referrerpolicy
属性は、リファラポリシー属性である。その目的は、スクリプトをフェッチするときに使用されるリファラポリシーと、そこからインポートされたスクリプトを設定することにある。[REFERRERPOLICY]
An example of a script
element's referrer policy being used when fetching imported scripts but not other subresources:
< 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 >
The blocking
attribute is a blocking attribute.
The fetchpriority
attribute is a fetch priority attribute. Its purpose is to set the priority used when fetching the script.
Changing the src
, type
, nomodule
, async
, defer
, crossorigin
, integrity
, referrerpolicy
, and fetchpriority
attributes dynamically has no direct effect; these attributes are only used at specific times described below.
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.
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:
If this's force async is true, then return true.
If this's async
content attribute is present, then return true.
Return false.
The async
setter steps are:
Set this's force async to false.
If the given value is true, then set this's async
content attribute to the empty string.
script.text [ = value ]
要素の子テキストコンテンツを返す。
与えられた値を持つ要素の子を置換するために、設定できる。
HTMLScriptElement
.supports(type)
Returns true if the given type is a script type supported by the user agent. The possible script types in this specification are "classic
", "module
", and "importmap
", but others might be added in the future.
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.
The supports(type)
method steps are:
If type is "classic
", then return true.
If type is "module
", then return true.
If type is "importmap
", then return true.
Return false.
The type argument has to exactly match these values; we do not perform an ASCII case-insensitive match. This is different from how type
content attribute values are treated, and how DOMTokenList
's supports()
method works, but it aligns with the WorkerType
enumeration used in the Worker()
constructor.
次の例において、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 >
The following sample shows how a script
element can be used to include an external JavaScript module script.
< script type = "module" src = "app.mjs" ></ script >
このモジュール、およびそのすべての依存関係(ソースファイル内のJavaScript import
文を通して表現される)は、フェッチされる。一度、全体の結果としてモジュールグラフがインポートされ、かつ文書が解析を完了したら、app.mjs
のコンテンツは評価される。
Additionally, if code from another script
element in the same Window
imports the module from app.mjs
(e.g. via import "./app.mjs";
), then the same JavaScript module script created by the former script
element will be imported.
This example shows how to include a JavaScript module script for modern user agents, and a classic script for older user agents:
< script type = "module" src = "app.mjs" ></ script >
< script nomodule defer src = "classic-app-bundle.js" ></ script >
In modern user agents that support JavaScript module scripts, the script
element with the nomodule
attribute will be ignored, and the script
element with a type
of "module
" will be fetched and evaluated (as a JavaScript module script). 逆に、古いユーザエージェントは、"module
"のtype
をもつscript
要素を、そのスクリプトタイプを未知のものとして無視するが、nomodule
属性を実装しないため、他のscript
要素を(クラシックスクリプトとして)取り出して評価することは問題ない。
The following sample shows how a script
element can be used to write an inline JavaScript module script that performs a number of substitutions on the document's text, in order to make for a more interesting reading experience (e.g. on a news site): [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 >
Some notable features gained by using a JavaScript module script include the ability to import functions from other JavaScript modules, strict mode by default, and how top-level declarations do not introduce new properties onto the global object. 両方の文書の解析が完了し、およびその依存関係(dom-utils.mjs
)がフェッチされかつ評価されるまで、このscript
要素が文書に表示されるかを問わず、評価されないことにも注意する。
The following sample shows how a JSON module script can be imported from inside a JavaScript module script:
< 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 type checking for module scripts is strict. In order for the fetch of the JSON module script to succeed, the HTTP response must have a JSON MIME type, for example Content-Type: text/json
. On the other hand, if the with { type: "json" }
part of the statement is omitted, it is assumed that the intent is to import a JavaScript module script, and the fetch will fail if the HTTP response has a MIME type that is not a JavaScript MIME type.
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:
Set el's result to result.
If el's steps to run when the result is ready are not null, then run them.
Set el's steps to run when the result is ready to null.
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.
The script
HTML element post-connection steps, given insertedNode, are:
If insertedNode is not connected, then return.
This can happen in the case 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. It removes the second script
, so that by the time its HTML element post-connection steps run, it is no longer connected, and does not get prepared.
If insertedNode is parser-inserted, then return.
Prepare the script element given insertedNode.
The script
children changed steps are:
Run the script
HTML element post-connection steps, given the script
element.
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:
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.
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.
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:
If namespace is not null, then return.
If localName is src
, then run the script
HTML element post-connection steps, given element.
To prepare the script element given a script
element el:
If el's already started is true, then return.
Let parser document be el's parser document.
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.
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.
Let source text be el's child text content.
If el has no src
attribute, and source text is the empty string, then return.
If el is not connected, then return.
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
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.
If the script block's type string is a JavaScript MIME type essence match, then set el's type to "classic
".
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
".
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
".
Otherwise, return. (No script is executed, and el's type is left as null.)
If parser document is non-null, then set el's parser document back to parser document and set el's force async to false.
Set el's already started to true.
Set el's preparation-time document to its node document.
If parser document is non-null, and parser document is not equal to el's preparation-time document, then return.
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]
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.
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]
If el has an event
attribute and a for
attribute, and el's type is "classic
", then:
Let for be the value of el's for
attribute.
Let event be the value of el's event
attribute.
Strip leading and trailing ASCII whitespace from event and for.
If for is not an ASCII case-insensitive match for the string "window
", then return.
If event is not an ASCII case-insensitive match for either the string "onload
" or the string "onload()
", then return.
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.
Let classic script CORS setting be the current state of el's crossorigin
content attribute.
Let module script credentials mode be the CORS settings attribute credentials mode for el's crossorigin
content attribute.
Let cryptographic nonce be el's [[CryptographicNonce]] internal slot's value.
If el has an integrity
attribute, then let integrity metadata be that attribute's value.
Otherwise, let integrity metadata be the empty string.
Let referrer policy be the current state of el's referrerpolicy
content attribute.
Let fetch priority be the current state of el's fetchpriority
content attribute.
Let parser metadata be "parser-inserted
" if el is parser-inserted, and "not-parser-inserted
" otherwise.
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.
Let settings object be el's node document's relevant settings object.
If el has a src
content attribute, then:
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.
Let src be the value of el's src
attribute.
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.
Set el's from an external file to true.
Let url be the result of encoding-parsing a URL given src, relative to el's node document.
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.
If el is potentially render-blocking, then block rendering on el.
Set el's delaying the load event to true.
If el is currently render-blocking, then set options's render-blocking to true.
Let onComplete given result be the following steps:
Mark as ready el given result.
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.
If el does not have a src
content attribute:
Let base URL be el's node document's document base URL.
Switch on el's type:
classic
"Let script be the result of creating a classic script using source text, settings object, base URL, and options.
Mark as ready el given script.
module
"Set el's delaying the load event to true.
If el is potentially render-blocking, then:
Block rendering on el.
Set options's render-blocking to true.
Fetch an inline module script graph, given source text, base URL, settings object, options, and with the following steps given result:
Queue an element task on the networking task source given el to perform the following steps:
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
"Let result be the result of creating an import map parse result given source text and base URL.
Mark as ready el given result.
If el's type is "classic
" and el has a src
attribute, or el's type is "module
":
If el has an async
attribute or el's force async is true:
Let scripts be el's preparation-time document's set of scripts that will execute as soon as possible.
Append el to scripts.
Set el's steps to run when the result is ready to the following:
Remove el from scripts.
Otherwise, if el is not parser-inserted:
Let scripts be el's preparation-time document's list of scripts that will execute in order as soon as possible.
Append el to scripts.
Set el's steps to run when the result is ready to the following:
If scripts[0] is not el, then abort these steps.
While scripts is not empty, and scripts[0]'s result is not "uninitialized
":
Execute the script element scripts[0].
Remove scripts[0].
Otherwise, if el has a defer
attribute or el's type is "module
":
Append el to its parser document's list of scripts that will execute when the document has finished parsing.
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.)
Otherwise:
Set el's parser document's pending parsing-blocking script to el.
Block rendering on el.
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.)
Otherwise:
If all of the following are true:
classic
";then:
Set el's parser document's pending parsing-blocking script to el.
Set el's ready to be parser-executed to true. (The parser will handle executing the script.)
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:
Let document be el's node document.
If el's preparation-time document is not equal to document, then return.
Unblock rendering on el.
If el's result is null, then fire an event named error
at el, and return.
If el's from an external file is true, or el's type is "module
", then increment document's ignore-destructive-writes counter.
Switch on el's type:
classic
"Let oldCurrentScript be the value to which document's currentScript
object was most recently set.
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.
Run the classic script given by el's result.
Set document's currentScript
attribute to oldCurrentScript.
module
"Assert: document's currentScript
attribute is null.
Run the module script given by el's result.
importmap
"Register an import map given el's relevant global object and el's result.
Decrement the ignore-destructive-writes counter of document, if it was incremented in the earlier step.
If el's from an external file is true, then fire an event named load
at el.
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.
Servers should use text/javascript
for JavaScript resources, in accordance with Updates to ECMAScript Media Types. Servers should not use other JavaScript MIME types for JavaScript resources, and must not use non-JavaScript MIME types. [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]
script
elementsThe easiest and safest way to avoid the rather strange restrictions described in this section is to always escape an ASCII case-insensitive match for "<!--
" as "\x3C!--
", "<script
" as "\x3Cscript
", and "</script
" as "\x3C/script
" when these sequences appear in literals in scripts (e.g. in strings, regular expressions, or comments), and to avoid writing code that uses such constructs in expressions. この節の制限がトリガーになりやすい落とし穴を回避する:すなわち、歴史的な理由のために、HTMLにおけるscript
ブロックの解析は、これらのシーケンスを考えた場合に直観的でない働きをする奇妙で風変わりな慣習である。
The script
element's descendant text content must match the script
production in the following ABNF, the character set for which is Unicode. [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) { ... }
これを行うとはまた、同様に様々な落とし穴を回避する:関連する歴史的な理由のために、クラシックスクリプトで文字列"<!--"は、"//"のように、実際には行コメントの開始として扱われる。
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 >
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:
When an XSLT transformation program is triggered by an <?xml-stylesheet?>
processing instruction and the browser implements a direct-to-DOM transformation, script
elements created by the XSLT processor need to have its parser document set correctly, and run in document order (modulo scripts marked defer
or async
), immediately, as the transformation is occurring.
The XSLTProcessor
transformToDocument()
method adds elements to a Document
object with a null browsing context, and, accordingly, any script
elements they create need to have their already started set to true in the prepare the script element algorithm and never get executed (scripting is disabled). Such script
elements still need to have their parser document set, though, such that their async
IDL attribute will return false in the absence of an async
content attribute.
The XSLTProcessor
transformToFragment()
method needs to create a fragment that is equivalent to one built manually by creating the elements using document.createElementNS()
. For instance, it needs to create script
elements with null parser document and with their already started set to false, so that they will execute when the fragment is inserted into a document.
The main distinction between the first two cases and the last case is that the first two operate on Document
s and the last operates on a fragment.
noscript
elementSupport in all current engines.
noscript
要素が存在しない場合、HTML文書のhead
要素内。noscript
要素が存在しない場合、HTML文書でフレージングコンテンツが期待される場所。head
要素内で:任意の順で、0個以上のlink
要素、ゼロ個以上のstyle
要素、0個以上のmeta
要素。head
要素外で:透過的。ただし、noscript
要素の子孫を持ってはならない。HTMLElement
を使用する。noscript
要素は、スクリプトが有効である場合は何も表さず、スクリプトが無効である場合は要素の子を表す。これは、文書が解析される方法に影響を与えることによって、スクリプトをサポートするユーザーエージェントとサポートしないユーザーエージェントに異なるマークアップを提示するために使用される。
HTML文書で使用する場合、許可されるコンテンツモデルは次のとおり:
head
要素内のnoscript
要素に対してhead
要素内のnoscript
要素に対してnoscript
要素は、テキストのみを含まなければならない。ただし、context要素としてnoscript
要素をもつHTML断片解析アルゴリズムを呼び出すものかつinputのようなテキストコンテンツがnoscript
要素の子であった場合、link
、style
、meta
要素のみからなるノードのリストをもたらさなければならない場合を除く。そして解析エラーでない。
head
要素外のnoscript
要素に対してnoscript
要素のコンテンツモデルは透過的であり、同時にnoscript
要素がnoscript
要素を持ってはならない(noscript
要素を入れ子にできない)追加制限がある。
head
要素外のnoscript
要素に対してnoscript
要素はテキストのみを含まなければならない。ただしテキストは、以下のアルゴリズムがnoscript
要素およびscript
要素をもたない適合文書をもたらすものでなければならず、アルゴリズムでステップは例外を投げるまたはHTMLパーサに解析エラーを起こさないようにしなければならない:
歴史的な理由により、パーサが呼び出されたときにスクリプトが有効にされたかどうかに基づくHTMLパーサによってnoscript
要素が異なる方法で処理されるので、これらのすべてのこじつけが必要とされる。
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 >
template
elementSupport in all current engines.
Support in all current engines.
span
属性を持たないcolgroup
要素の子として。shadowrootmode
— Enables streaming declarative shadow rootsshadowrootdelegatesfocus
— Sets delegates focus on a declarative shadow rootshadowrootclonable
— Sets clonable on a declarative shadow rootshadowrootserializable
— Sets serializable on a declarative shadow root[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の断片を宣言するために使用される。
The shadowrootmode
content attribute is an enumerated attribute with the following keywords and states:
キーワード | 状態 | 概要 |
---|---|---|
open | open | The template element represents an open declarative shadow root. |
closed | closed | The 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
Support in all current engines.
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:
Let doc be the template
element's node document's appropriate template contents owner document.
Create a DocumentFragment
object whose node document is doc and host is the template
element.
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:
If doc is not a Document
created by this algorithm, then:
If doc does not yet have an associated inert template document, then:
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.
If doc is an HTML document, mark new doc as an HTML document also.
Let doc's associated inert template document be new doc.
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.
Return doc.
The adopting steps (with node and oldDocument as parameters) for template
elements are the following:
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.
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:
If the clone children flag is not set in the calling clone algorithm, return.
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.
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()
とともに更新される。
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:
An XSLT processor based on an XML parser that acts as described in this specification needs to act as if template
elements contain as descendants their template contents for the purposes of the transform.
An XSLT processor that outputs a DOM needs to ensure that nodes that would go into a template
element are instead placed into the element's template contents.
XPath evaluation using the XPath DOM API when applied to a Document
parsed using the HTML parser or the XML parser described in this specification needs to ignore template contents.
slot
elementSupport in all current engines.
Support in all current engines.
name
— シャドウツリースロットの名前[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
Support in all current engines.
slot.assignedNodes()
Support in all current engines.
slot.assignedNodes({ flatten: true })
slot
要素が存在しなくなるまで、再帰的に、slot
要素に遭遇するのと同じものを返す。slot.assignedElements()
HTMLSlotElement/assignedElements
Support in all current engines.
slot.assignedElements({ flatten: true })
assignedNodes({ flatten: true })
と同じものを返す。slot.assign(...nodes)
Sets slot's manually assigned nodes to the given nodes.
name
IDL属性は、同じ名前のコンテンツ属性を反映しなければならない。
The slot
element has manually assigned nodes, which is an ordered set of slottables set by assign()
. This set is initially empty.
The manually assigned nodes set can be implemented using weak references to the slottables, because this set is not directly accessible from script.
The assignedNodes(options)
method steps are:
If options["flatten
"] is false, then return this's assigned nodes.
Return the result of finding flattened slottables with this.
The assignedElements(options)
method steps are:
If options["flatten
"] is false, then return this's assigned nodes, filtered to contain only Element
nodes.
Return the result of finding flattened slottables with this, filtered to contain only Element
nodes.
Support in all current engines.
The assign(...nodes)
method steps are:
For each node of this's manually assigned nodes, set node's manual slot assignment to null.
Let nodesSet be a new ordered set.
For each node of nodes:
If node's manual slot assignment refers to a slot, then remove node from that slot's manually assigned nodes.
Set node's manual slot assignment to this.
Append node to nodesSet.
Set this's manually assigned nodes to nodesSet.
Run assign slottables for a tree for this's root.