HTML <script>
Tag
Example
Output "Hello world" using JavaScript:
<script>
document.write("Hello World!")
</script>
Browser Support
All major browsers support the <script>
tag.
Tag Definition and Usage
The <script>
tag is used to define client-side scripts, such as JavaScript.
The <script>
element either contains scripting statements or it points to an external script file through the src
attribute.
JavaScript is commonly used for image manipulation, form validation, and dynamic content updates.
Tips and Notes
Note: If the src
attribute is used, the <script>
element must be empty.
Tip: See the <noscript>
element for users who have disabled scripts in their browser or whose browser does not support client-side scripting.
Note: There are several ways to execute external scripts:
If
async="async"
: The script is executed asynchronously with the rest of the page (the script will be executed while the page continues to parse)If
async
is not used anddefer="defer"
: The script will be executed when the page has finished parsingIf neither
async
nordefer
is used: The script is fetched and executed immediately before the page continues to parse
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 that were supported in HTML 4.01 are no longer supported in HTML5: xml:space
.
Differences Between HTML and XHTML
In XHTML, the content type declaration is #PCDATA
(instead of CDATA
), meaning entities will be parsed.
This means that all special characters should be encoded or all content should be nested within a CDATA
section in XHTML:
<script type="text/javascript">
//<![CDATA[
var i=10;
if (i<5)
{
// code content
}
//]]>
</script>
Attributes
Attribute | Value | Description |
---|---|---|
async New | async | Specifies that the script is executed asynchronously (only for external scripts). |
charset | charset | Specifies the character encoding used in the script (only for external scripts). |
defer | defer | Specifies that the script is executed when the page has finished parsing (only for external scripts). |
src | URL | Specifies the URL of an external script. |
type | MIME-type | Specifies the MIME type of the script. |
xml:space | preserve | Not supported in HTML5. Specifies whether to preserve white space in the code. |
Global Attributes
The <script>
tag supports HTML's global attributes.
Related Articles
HTML Tutorial: HTML Scripts