HTML script tag
Example
Write "Hello JavaScript!" with JavaScript:
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
Definition and Usage
The <script>
tag is used to embed a client-side script (JavaScript).
The <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.
Browser Support
Element | |||||
---|---|---|---|---|---|
<script> | Yes | Yes | Yes | Yes | Yes |
Attributes
Attribute | Value | Description |
---|---|---|
async | async | Specifies 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 |
Sets the mode of the request to an HTTP CORS Request |
defer | defer | Specifies 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 | 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 |
Specifies 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 |
Specifies which referrer information to send when fetching a script |
src | URL | Specifies the URL of an external script file |
type | scripttype | Specifies 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.
PCDATA - PCDATA means parsed character data. Think of character data as the text found between the start tag and the end tag of an XML element. PCDATA is text that WILL be parsed by a parser. The text will be examined by the parser for entities and markup.
CDDATA - A CDATA section is used to mark a section of an XML document, so that the XML parser interprets it only as character data, and not as markup.
This means that in XHTML, all special characters should be encoded, or all content should be wrapped inside a CDATA section:
//<![CDATA[
var i = 10;
if (i < 5) {
// some code
}
//]]>
</script>
Global Attributes
The <script>
tag also supports the Global Attributes in HTML.
Default CSS Settings
Most browsers will display the <script>
element with the following default values:
display: none;
}
Comments
Post a Comment