HTML <script> Tag

The <script> tag declares client-side script (JavaScript) in an HTML document. The tag can include either the script itself, or a link to an external file containing scripts. The path to the external file is specified with src attribute.

If you connect an external file with scripts, don’t embed script into the same <script> tag.

The <script> tag can be placed in the <head> element, as well as within the <body> element. The script execution doesn’t depend on its location in an HTML document, but the scripts, that must be executed first, must be placed in the heading of the document.

The <script> tag can be used in an HTML document many times.

Syntax

The <script> tag comes in pairs; the closing tag (</script>) is required.

There are few ways an external script can be executed:

  • The async="async" attribute indicates, that the scripts is executed asynchronously, simultaneously with the loading of the page.
  • When there is no async and defer="defer", the script is executed after the loading of the page.
  • If there is no async and defer, the script is executed before the loading of the page.

Example

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <p id="example"></p>
    <script>
      document.getElementById("example").innerHTML = "My first JavaScript code";
    </script>
  </body>
</html>

Result

Attributes

Attribute Value Description
async async Defines that the script is executed asynchronously. (For external scripts only).
Not supported in IE9 and older versions.
charset charset Defines character encoding, used in an external file with the JavaScript code.
defer defer Defines, that the script must be executed after the loading of the page. (For external scripts only).
src URL Defines the URL of an external file with the JavaScript code. (Can be defined either relative, or an absolute URL).
type media_type Defines the MIME-type of the script.

The <script> tag supports the Global Attributes and the Event Attributes.

Browser support





Related articles