最适合网络开发者的网站
HTML5。英语版 W3Schools。完整标签指南

尿素

HTML <script> 标签


例子

Write "Hello JavaScript!" with JavaScript:

<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
亲自尝试 »

定义和用法

<script> tag is used to embed a client-side script (JavaScript).

<script> element either contains scripting statements, or it points to an external script file through the src attribute.

Common uses for JavaScript are image manipulation, form validation, and dynamic changes of content.


Tips and Notes

Tip: Also look at the <noscript> element for users that have disabled scripts in their browser, or have a browser that doesn't support client-side scripting.

Tip: If you want to learn more about JavaScript, visit our JavaScript 教程.


浏览器支持

元素
<script> 是的 是的 是的 是的 是的

Attributes

Attribute Value 描述
async async Specify 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
Set the mode of the request to an HTTP CORS Request
defer defer Specify 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 It 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
Specify 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
Specify which referrer information to send when fetching a script
src URL Specify the URL of an external script file
type scripttype Specify the media type of the script

Differences Between HTML and XHTML

In XHTML, the content inside scripts is declared as #PCDATA (instead of CDATA), which means that entities will be parsed.

This means that in XHTML, all special characters should be encoded, or all content should be wrapped inside a CDATA section:

<script type="text/javascript">
//<![CDATA[
let i = 10;
if (i < 5) {
  // some code
}
//]]>
</script>

全局属性

<script> 标签还支持HTML 中的全局属性.


相关页面

HTML tutorial: HTML Scripts

HTML DOM 参考: Script Object

JavaScript Tutorial: 学习 JavaScript


默认 CSS 设置

大多数浏览器会显示 <script> 元素具有以下默认值:

script {
  display: none;
}