Topic: HTML5 Tags ReferencePrev|Next
<script> tag may appear any number of times in the
<body> of an HTML document.
<script> element either contains a series of scripting statements, or it points to an external script file (through the
src attribute) that's processed on the client side (user's computer) to add interactivity or affect the behavior of web pages.
The following table summarizes the usages context and the version history of this tag.
|Placement:||Inline (but can also be contained in
|Start/End Tag:||Start tag: required, End tag: required|
|Version:||HTML 4, 4.01, 5|
The basic syntax of the
<script> tag is given with:
The example below shows the
<script> tag in action.
ExampleTry this code »
<script> document.write("Hello World!"); </script>
There are some important differences in the way that HTML and XHTML deal with the content inside the scripts. In HTML, the content type is declared as
CDATA, which means that HTML entities will not be parsed. However, in XHTML, the content type is declared as
#PCDATA, which means that entities will be parsed.
To ensure that the content inside the opening
<script> and closing
</script> tags parses correctly when it is included within an XHTML document, all special characters should be encoded — for example, ampersands (
&) should be encoded as
&, and greater-than (
>) symbols should be encoded as
> and so on, or all content should be wrapped inside a CDATA section like this:
ExampleTry this code »
Note: If the
src attribute is specified, the
<script> element should not have a script embedded within its tags.
The following table shows the attributes that are specific to the
||This Boolean attribute specifies that the script should be executed asynchronously, as soon as it becomes available. Only for external scripts, it has no effect on inline scripts.|
||content-type||Specifies the language of the script. The most common value is
||charset||Specifies the character encoding of the external script file. This attribute must not be specified if
||This boolean attribute Specifies that script should be executed after the document has been parsed. This attribute shouldn't be used on scripts that don't have the
||URL||Specifies the location of an external script file.|
||Obsolete Specifies whether whitespace should be preserved within the script element.|
Like all other HTML tags, the
<script> tag supports the global attributes in HTML5.
<script> tag also supports the event attributes in HTML5.
<script> tag is supported in all major modern browsers.
Tip: Check out the
<noscript> element which provides an alternate content for users that have either disabled scripts in their browser or have a browser that doesn't support client-side scripting.
See tutorial on: HTML Script.