HTML <script>Tag


Examples

Output "Hello world" via JavaScript:

<script> document.write("Hello World!") </script>

Try it Yourself »

Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support the <script> tag.


Tag Definition and Usage Instructions

The <script> tag is used to define client-side scripts, such as JavaScript.

The <script> element can either contain script statements, or point to an external script file through the "src" attribute.

JavaScript is commonly used for image manipulation, form validation, and dynamic content changes.


Tips and Notes

Note:If the "src" attribute is used, the <script> element must be empty.

Tip:See also<noscript>element, which is very useful for users who have disabled scripts in their browser or whose browser does not support client-side scripts.

Note:There are several ways to execute external scripts:

  • If async="async": the script is executed asynchronously relative to the rest of the page (the script will be executed while the page continues parsing)
  • If async is not used and defer="defer": the script will be executed when the page has finished parsing
  • If neither async nor defer is used: the script is read and executed immediately before the browser continues parsing the page

Differences between HTML 4.01 and HTML5

In HTML 4, the "type" attribute is required, but in HTML5 it is optional.

The "async" attribute is new in HTML5.

Some attributes from HTML 4.01 are no longer supported in HTML5: "xml:space".


Differences between HTML and XHTML

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

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

<script type="text/javascript">
//<![CDATA[
var i=10;
if (i<5)
{
    // 代码内容
}
//]]>
</script>


Attributes

New: New in HTML5.

Attribute Value Description
asyncNew async Specifies that the script is executed asynchronously (only applicable to external scripts).
charset charset Specifies the character encoding used in the script (only applicable to external scripts).
defer defer Specifies that the script is executed after the page has finished parsing (only applicable to external scripts).
src URL Specifies the URL of the external script.
type MIME-type Specifies the MIME type of the script.
xml:space preserve Not supported in HTML5.Specifies whether to preserve whitespace in the code.


Global Attributes

The <script> tag supportsHTML Global Attributes。


Related Articles

HTML Tutorial:HTML Scripts

Other Extensions