This reference is built into PageRIJ — a live HTML, CSS & SVG authoring and learning environment.

HTML <script> element

The <script> element includes executable scripts, script-related instructions, or data blocks in an HTML document. Its usual purpose is to connect JavaScript to the page. It can occur in the <head> or <body>.

JavaScript can be written between the opening and closing tags or loaded from a file with src. When src is used, executable code belongs in that file rather than between the tags. A closing tag is required in either case.

Omitting type selects classic JavaScript. During ordinary HTML parsing, a classic script without async or defer runs when encountered, pausing parsing; an external file must first be fetched. Such a script can access elements already parsed, as the example below demonstrates.

For external classic scripts, defer allows fetching while parsing continues, then executes the scripts in document order after parsing finishes. With async, execution occurs as soon as each script is ready, potentially before parsing finishes and without document-order guarantees. These attributes do not defer an inline classic script.

The value type="module" selects a JavaScript module. Modules encountered during parsing normally run after parsing, without needing defer. Adding async allows a module to run once it and its dependencies are ready. The nomodule attribute marks a classic script to be skipped by browsers that support modules.

The element can also hold non-executable material. The types importmap and speculationrules provide JSON instructions for module resolution and speculative loading respectively. A data block such as type="application/json" holds data for other code or tools to read; it is not executed as JavaScript.

Resource-related attributes include crossorigin for cross-origin request handling, referrerpolicy for referrer information, integrity for checking a fetched script against a hash, and fetchpriority for a fetching-priority hint. Where applicable, blocking="render" requests that rendering wait for the script. Which attributes apply depends on the script type and whether it is external.

The example places a script after a <p> and changes that paragraph’s text. The script itself has no visible box; the result is the updated paragraph.

Attributes: type, src, nomodule, async, defer, blocking, crossorigin, referrerpolicy, integrity, fetchpriority, GLOBALS.

Typical layout:
<p id="script-message">Waiting for the script.</p>
<script>
  document.getElementById("script-message").textContent = "The script has run.";
</script>
Visual representation:

Waiting for the script.