Detailed usage of HTML tags

Time:2019-10-9

HTML <script>Label function

<script>Tags are used to define client scripts, such as JavaScript.

<script>Elements can contain script statements or point to external script files through the “src” attribute.

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


HTML <script>Label usage

Output “Hello world” through JavaScript:

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

Browser support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All mainstream browsers support<script>Label.


Tips and Notes

Note: If the “src” attribute is used, then<script>Elements must be empty.

Tip: See<noscript>Element is very useful for users who disable scripts in browsers or whose browsers do not support client scripts.

Note: There are several ways to execute external scripts:

  • If async = “async”: the script executes asynchronously relative to the rest of the page (when the page continues to parse, the script will be executed)
  • If you don’t use async and defer= “defer”: The script will execute when the page is parsed
  • If you don’t use either async or defer: Read and execute the script immediately before the browser continues to parse the page

Differences between HTML4 and HTML5

In HTML 4, the “type” attribute is required, but is optional in HTML5.

The “async” attribute is a new attribute in HTML5.

Some attributes in HTML4 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 is parsed.

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

<script type="text/javascript">
//<![CDATA[
var i=10;
if (i<5)
{
    // Code content
}
//]]>
</script>

attribute

New: New attributes in HTML5.

attribute value describe
asyncNew async Provide for asynchronous execution of scripts (only for external scripts).
charset charset Specifies the character encoding to be used in scripts (only for external scripts).
defer defer Provides that when the page has been parsed, the script is executed (only for external scripts).
src URL Specify the URL of the external script.
type MIME-type Specify the MIME type of the script.
xml:space preserve HTML5 is not supported. Specifies whether to retain the blanks in the code.

Global attributes

<script>Tags support HTML global properties.

Related articles

HTML tutorial: HTML scripts

This article refers to HTML Chinese Help Document