<script>
HTML <script> Tag
Instance
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <script> document.write("Hello World!") </script> </body> </html>
Run Example»
Click the "Run Instance" button to view the online instance
Browser support
All major browsers support< script> tag.
Tag definition and usage instructions
<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
Notes: If the "src" attribute is used, the <script> element must be empty.
Tip: See the <noscript> element, which is useful for users who have disabled scripting in their browsers or whose browsers do not support client-side scripting.
Notes: There are multiple 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 when the page continues to be parsed)
- If async is not used and defer="defer": the script will be executed when the page completes parsing
- If neither async nor defer is used Use defer: Read and execute the script immediately before the browser continues to parse the page
Differences between HTML 4.01 and HTML5
In HTML 4, "type " attribute is required, but is optional in HTML5.
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 in the script is declared as #PCDATA (instead of CDATA), which means that the entity will be parsed.
This means that in XHTML, all special characters should be encoded, or everything should be nested in a CDATA section:
//<![CDATA[
var i=10;
if (i<5)
{
// some code
}
//]]>
</script>
Attribute
New: New attribute in HTML5.
Properties | Value | Description |
---|---|---|
asyncNew | async | Specifies to execute the script asynchronously (applies to external scripts only). |
charset | charset | Specifies the character encoding used in the script (applies to external scripts only). |
defer | defer | Specifies that the script is executed when the page has finished parsing (applies to external scripts only). |
src | URL | Specifies the URL of the external script. |
type | MIME-type | Specifies the MIME type of the script. |
xml:space | preserve | HTML5 is not supported. Specifies whether to preserve whitespace in the code. |
Global attributes
The<script> tag supports global attributes of HTML.
Related Articles
HTML Tutorial: HTML Script