Description
The HTML element <script> is used to embed or reference an executable client-side script, like JavaScript within an HTML document.
- It can contain a series of scripting statements, which we call internal scripts.
- It can point or refer to an external script file using its
srcattribute.
It can appear any number of times within the <head> and <body> elements.
Scripts make a web page dynamic and interactive to the actions performed by users.
The below table summarizes its usage.
| Usage Details | |
| Placement | It can be included anywhere within <head> and <body> elements. |
| Contents | It can contain text. |
| Tags | Both the opening and closing tags are required. |
| Versions | HTML 4, 4.01, 5 |
Syntax
Here is the basic syntax of the <script> element.
<script>...</script>
Examples
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example - HTML Element script</title>
</head>
<body>
<script>
document.write("Hello World!");
</script>
</body>
</html>
Attributes
The following table shows the list of supported and unsupported attributes for the <script> element.
| Attribute Type | Details |
| Element-Specific Attributes | The tag <script> has some element-specific attributes listed in the below table. |
| Global Attributes | Like all other HTML tags, the tag <script> supports the HTML Global Attributes. |
| Event Attributes | The tag <script> also supports the HTML Event Attributes. |
Here is a list of attributes that are specific to the <script> element.
| Attribute | Value | Required | Description |
async |
async |
No | Boolean attribute that specifies whether the script should be executed asynchronously, as soon as it becomes available. Applicable only for external scripts, it has no effect on inline scripts. |
type |
content-type | No | Specifies the scripting language. The most common scripting language is JavaScript, which needs the value text/javascript. |
charset |
charset | No | Specifies the character encoding of the external script file. This attribute must not be specified if the src attribute is not present. |
defer |
defer |
No | Boolean attribute that specifies whether the script should be executed after the document has been parsed. This attribute shouldn't be used on scripts that don't have the src attribute. |
src |
URL | No | Specifies the location of an external script file. |
xml:space |
preserve |
No | Obsolete Specifies whether whitespace should be preserved within the script element. |
Browser Compatibility
The tag <script> is supported in all modern browsers.
- Google Chrome 1+
- Internet Explorer or Edge 3+
- Firefox 1+
- Apple Safari 1+
- Opera 4+