Edition for Web Developers — Last Updated 9 June 2025
スクリプトは著者が文書に双方向性を追加することを許可する。
著者は、宣言型のメカニズムがしばしばより保守しやすく、かつ多くのユーザーがスクリプトを無効としているため、可能であれば、スクリプトに宣言型の代替を使用するよう推奨される。
たとえば、より詳細な情報を表示するセクションを表示または非表示にするスクリプトを使用する代わりに、details
要素を使用できる。
著者はまた、スクリプトのサポートがない状態でそれらのアプリケーションが行儀よくデグレードするよう推奨される。
たとえば、著者がテーブルヘッダーにおいてリンクに動的なテーブルの再ソートを提供する場合、リンクはまたサーバーからソートされたテーブルを要求することによって、スクリプトなしで機能させることができるかもしれない。
script
要素Support in all current engines.
src
属性が存在しない場合、type
属性の値に依存するが、スクリプトの内容制限に一致しなければならない。src
属性が存在する場合、要素は空またはスクリプト文書を含むだけでなくスクリプトの内容制限に一致するかのいずれかでなければならない。type
— スクリプトの種類src
— リソースのアドレスnomodule
— モジュールスクリプトをサポートするユーザーエージェントにおける実行を防ぐasync
— フェッチの間ブロックなしで、可能な場合にスクリプトを実行するdefer
— スクリプトの実行を延期するblocking
— 要素が潜在的にレンダリングブロッキングであるかどうか crossorigin
— 要素が生成元をまたいだ要求を処理する方法referrerpolicy
— 要素によって開始されたフェッチのためのリファラーポリシーintegrity
— Subresource Integrityチェックで使用される整合性メタデータ[SRI]fetchpriority
— 要素によって開始されるフェッチの優先度を設定するHTMLScriptElement
を使用する。The script
element allows authors to include dynamic script, instructions to the user agent, and data blocks in their documents. この要素は、ユーザーにコンテンツを表すものでない。
Support in all current engines.
The script element has two core attributes. type
属性は、表されるスクリプトの型のカスタマイズを可能にする:
Omitting the attribute, setting it to the empty string, or setting it to a JavaScript MIME type essence match means that the script is a classic script, to be interpreted according to the JavaScript Script top-level production. Authors should omit the type
attribute instead of redundantly setting it.
"module
"にASCII大文字・小文字不区別で一致する属性を設定することは、スクリプトがJavaScript Moduleトップレベル制作物によって解釈されるようなJavaScriptモジュールスクリプトであることを意味する。
"importmap
"とASCII大文字・小文字不区別で一致する属性を設定することは、スクリプトがモジュール指定子解決の動作を制御するために使用されるJSONを含むインポートマップであることを意味する。
Setting the attribute to any other value means that the script is a data block, which is not processed by the user agent, but instead by author script or other tools. Authors must use a valid MIME type string that is not a JavaScript MIME type essence match to denote data blocks.
データブロックが妥当なMIMEタイプ文字列を使用して表記されなければならない要件は、潜在的な将来の衝突を回避するための場所である。Values for the type
attribute that are not MIME types, like "module
" or "importmap
", are used by the standard to denote types of scripts which have special behavior in user agents. 現在に妥当なMIMEタイプ文字列を使用することで、将来のユーザーエージェントでさえも、データブロックが異なるスクリプトタイプとして再解釈されないことを保証する。
The second core attribute is the src
attribute. It must only be specified for classic scripts and JavaScript module scripts, and denotes that instead of using the element's child text content as the script content, the script will be fetched from the specified URL. If src
is specified, it must be a valid non-empty URL potentially surrounded by spaces.
Which other attributes may be specified on a given script
element is determined by the following table:
nomodule | async | defer | blocking | crossorigin | referrerpolicy | integrity | fetchpriority | |
---|---|---|---|---|---|---|---|---|
External classic scripts | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
Inline classic scripts | Yes | · | · | · | Yes* | Yes* | · | ·† |
External module scripts | · | Yes | · | Yes | Yes | Yes | Yes | Yes |
Inline module scripts | · | Yes | · | · | Yes* | Yes* | · | ·† |
Import maps | · | · | · | · | · | · | · | · |
Data blocks | · | · | · | · | · | · | · | · |
* Although inline scripts have no initial fetches, the crossorigin
and referrerpolicy
attribute on inline scripts affects the credentials mode and referrer policy used by module imports, including dynamic import()
.
† Unlike crossorigin
and referrerpolicy
, fetchpriority
does not affect module imports. See some discussion in issue #10276.
インラインscript
要素、または外部スクリプトリソースのコンテンツは、それぞれクラシックスクリプトおよびJavaScriptモジュールスクリプトに対するJavaScript仕様のScriptまたはModule生成物の要件に適合しなければならない。[JAVASCRIPT]
インポートマップのインラインscript
要素のコンテンツは、インポートマップのオーサリング要件に適合しなければならない。
データブロックを含めるために使用される場合、データは、インラインに埋め込まれなければならず、データの形式は、type
属性を使用して指定しなければならず、かつscript
要素のコンテンツは、使用される形式のために定義される要件に適合しなければならない。
nomodule
属性は、モジュールスクリプトをサポートするユーザーエージェントでスクリプトが実行されないようにする真偽属性である。これは、以下に示すように、モダンなユーザーエージェントのモジュールスクリプトと古いユーザーエージェントのクラシックスクリプトの選択的な実行を可能にする。
Support in all current engines.
Support in all current engines.
async
およびdefer
属性は、どのようにスクリプトが評価されるべきかを示す真偽属性である。There are several possible modes that can be selected using these attributes, depending on the script's type.
For external classic scripts, if the async
attribute is present, then the classic script will be fetched in parallel to parsing and evaluated as soon as it is available (potentially before parsing completes). async
が存在しないがdefer
属性が存在する場合、クラシックスクリプトは、並行してフェッチされ、ページが解析終了したときに評価される。いずれの属性も存在しない場合、スクリプトは、両方が完了するまで解析を阻止して、すぐにフェッチされ評価される。
モジュールスクリプトについて、async
属性が存在する場合、モジュールスクリプトとそのすべての依存関係は、構文解析と並行してフェッチされ、モジュールスクリプトは利用可能になるとすぐに(潜在的に構文解析が完了する前に)評価される。そうでなければ、モジュールスクリプトとその依存関係は、構文解析と並行してフェッチされ、ページが解析終了したときに評価される。(defer
属性は、モジュールスクリプトに影響しない。)
これは、次の模式図にすべて要約される:
document.write()
メソッドを使用して挿入するとき、通常はscript
要素が実行される(一般に、スクリプトの実行またはHTMLの解析をブロックする)。innerHTML
属性とouterHTML
属性を使用して挿入する場合、それらは一切実行されない。
たとえasync
属性が指定されても、デフォルトとなるブロッキング動作の代わりにdefer
の動作をフォールバックするために、defer
のみをサポートする(かつasync
をサポートしない)レガシーウェブブラウザーをもたらすため、defer
属性は指定されてもよい。
blocking
属性はブロッキング属性である。
crossorigin
属性はCORS設定属性である。For external classic scripts, it controls whether error information will be exposed, when the script is obtained from other origins. For external module scripts, it controls the credentials mode used for the initial fetch of the module source, if cross-origin. For both classic and module scripts, it controls the credentials mode used for cross-origin module imports.
クラシックスクリプトとは異なり、モジュールスクリプトは、生成元をまたいだフェッチのためにCORSプロトコルを使用する必要がある。
referrerpolicy
属性は、リファラーポリシー属性である。Its sets the referrer policy used for the initial fetch of an external script, as well as the fetching of any imported module scripts. [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 >
The integrity
attribute sets the integrity metadata used for the initial fetch of an external script. The value must match the requirements of the integrity attribute. [SRI]
fetchpriority
は、フェッチ優先度属性である。Its sets the priority used for the initial fetch of an external script.
Changing any of these attributes dynamically has no direct effect; these attributes are only used at specific times.
script.text [ = value ]
要素の子テキストコンテンツを返す。
script.text = value
Replaces the element's children with the text given by value.
HTMLScriptElement
.supports(type)
HTMLScriptElement/supports_static
Support in all current engines.
指定されたtypeがユーザーエージェントによってサポートされるスクリプトタイプである場合、trueを返す。この仕様で可能なスクリプトタイプは"classic
"、"module
"および"importmap
"であるが、将来的に他のタイプが追加される可能性がある。
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タイプを持つ場合にフェッチが失敗する。
サーバーは、Updates to ECMAScript Media Typesに従って、JavaScriptリソースにtext/javascript
を使用すべきである。サーバーは、JavaScriptリソースに他のJavaScript MIMEタイプを使用すべきではなく、非JavaScript MIMEタイプを使用してはならない。[RFC9239]
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) { ... }
これを行うとはまた、同様に様々な落とし穴を回避する:関連する歴史的な理由のために、クラシックスクリプトで文字列"<!--"は、"//"のように、実際には行コメントの開始として扱われる。
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 >
noscript
要素Support in all current engines.
noscript
要素が存在しない場合、HTML文書のhead
要素内。noscript
要素が存在しない場合、HTML文書でフレージングコンテンツが期待される場所。head
要素内で:任意の順で、0個以上のlink
要素、0個以上の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は、これを実行するためのメカニズムを定義しない。
次の例において、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
要素Support in all current engines.
span
属性を持たないcolgroup
要素の子として。shadowrootmode
— 宣言的なシャドウルートのストリーミングを有効にするshadowrootdelegatesfocus
— 宣言的なシャドウルートに代理フォーカスを設定するshadowrootclonable
— 宣言的なシャドウルートにクローン可能を設定するshadowrootserializable
— 宣言的なシャドウルートにシリアライズ可能を設定するshadowrootcustomelementregistry
— Enables declarative shadow roots to indicate they will use a custom element registryHTMLTemplateElement
を使用する。template
要素は、複製され、スクリプトによって文書に挿入できるHTMLの断片を宣言するために使用される。
shadowrootmode
コンテンツ属性は、次のキーワードおよび状態をもつ列挙属性である:
キーワード | 状態 | 概要 |
---|---|---|
open | Open | template要素は、開いた宣言的なシャドウルートを表す。 |
closed | Closed | template要素は、閉じた宣言的なシャドウルートを表す。 |
The shadowrootmode
attribute's invalid value default and missing value default are both the None state.
shadowrootdelegatesfocus
コンテンツ属性は、真偽属性である。
shadowrootclonable
コンテンツ属性は、真偽属性である。
shadowrootserializable
コンテンツ属性は、真偽属性である。
The shadowrootcustomelementregistry
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
テンプレートコンテンツ(DocumentFragment
)を返す。
この例において、スクリプトは、手動でマークアップから構造を生成する代わりに要素構造を提供するために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()
とともに更新される。
slot
要素Support in all current engines.
name
— シャドウツリースロットの名前HTMLSlotElement
を使用する。slot
要素は、スロットを定義する。典型的にシャドウツリーに使用される。もしあれば、slot
要素はその割り当てられるノードを表し、そうでなければそのコンテンツを表す。
name
コンテンツ属性は、任意の文字列値を含んでもよい。これはスロットの名前を表す。
slot
属性は、別の要素にスロットを割り当てるために使用される:name
属性をもつslot
要素は、その要素がそのname
属性の値と一致する値を持つslot
属性を持ち、かつslot
要素がその対応するslot
属性値を持つルートのホストを持つシャドウツリーの子である場合、任意の要素が割り当てられる名前付きスロットを作成する。
slot.name
slot.assignedNodes()
slot.assignedNodes({ flatten: true })
slot
要素が存在しなくなるまで、再帰的に、slot
要素に遭遇するのと同じものを返す。slot.assignedElements()
slot.assignedElements({ flatten: true })
assignedNodes({ flatten: true })
と同じものを返す。slot.assign(...nodes)
slotの手動で割り当てられたノードを、指定されたnodesに設定する。
name
IDL属性は、同じ名前のコンテンツ属性を反映しなければならない。
slot
要素は、manually assigned nodesを持ち、これは、 assign()
によって設定されたslottablesの順序付きセットである。このセットは、最初は空である。
manually assigned nodesセットは、スクリプトから直接アクセスできないため、slottablesへの弱い参照を使用して実装することができる。
The assignedNodes(options)
method steps are:
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.