HTML <script>タグ
例
「HelloJavaScript!」と書いてください。JavaScriptの場合:
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
定義と使用法
この<script>
タグは、クライアント側のスクリプト(JavaScript)を埋め込むために使用されます。
この<script>
要素にはスクリプトステートメントが含まれているか、src属性を介して外部スクリプトファイルを指しています。
JavaScriptの一般的な用途は、画像の操作、フォームの検証、コンテンツの動的な変更です。
ヒントと注意
ヒント:ブラウザでスクリプトを無効にしているユーザー、またはクライアント側のスクリプトをサポートしていないブラウザを使用しているユーザーの<noscript>要素も確認してください。
ヒント: JavaScriptについて詳しく知りたい場合は、JavaScriptチュートリアルにアクセスしてください。
ブラウザのサポート
Element | |||||
---|---|---|---|---|---|
<script> | Yes | Yes | Yes | Yes | Yes |
属性
Attribute | Value | Description |
---|---|---|
async | async | Specifies that the script is downloaded in parallel to parsing the page, and executed as soon as it is available (before parsing completes) (only for external scripts) |
crossorigin | anonymous use-credentials |
Sets the mode of the request to an HTTP CORS Request |
defer | defer | Specifies that the script is downloaded in parallel to parsing the page, and executed after the page has finished parsing (only for external scripts) |
integrity | filehash | Allows a browser to check the fetched script to ensure that the code is never loaded if the source has been manipulated |
nomodule | True False |
Specifies that the script should not be executed in browsers supporting ES2015 modules |
referrerpolicy | no-referrer no-referrer-when-downgrade origin origin-when-cross-origin same-origin strict-origin strict-origin-when-cross-origin unsafe-url |
Specifies which referrer information to send when fetching a script |
src | URL | Specifies the URL of an external script file |
type | scripttype | Specifies the media type of the script |
HTMLとXHTMLの違い
XHTMLでは、スクリプト内のコンテンツは(CDATAではなく)#PCDATAとして宣言されます。これは、エンティティが解析されることを意味します。
これは、XHTMLでは、すべての特殊文字をエンコードするか、すべてのコンテンツをCDATAセクション内にラップする必要があることを意味します。
<script type="text/javascript">
//<![CDATA[
var i = 10;
if (i < 5) {
// some code
}
//]]>
</script>
グローバル属性
この<script>
タグは、HTMLのグローバル属性もサポートしています。
関連ページ
HTMLチュートリアル:HTMLスクリプト
HTML DOMリファレンス:スクリプトオブジェクト
JavaScriptチュートリアル:JavaScriptを学ぶ
デフォルトのCSS設定
ほとんどのブラウザは<script>
、次のデフォルト値で要素を表示します。
script {
display: none;
}