HTML / HTML Tags

HTML <Script> Tag

Dec 12, 2022
3 min read
HTML script Tag

Definition

The <script> tag is used to embed a client-side script, such as JavaScript. It can either be embedded directly or through an external file using the src attribute.

Example

<script async src="https://cdn.ampproject.org/v0.js"></script>

Usage

Attributes

The Script element supports the Global Attributes, as well as the following:

  • async

    The async attribute is a boolean that determines whether the script should be fetched in parallel to HTML parsing and evaluated as soon as possible. The src attribute must be present, as this only applies to external scripts.

  • crossorigin

    The crossorigin attribute is a CORS setting attribute and controls whether error information will be exposed for external scripts from other origins.

  • defer

    The defer attribute is a boolean that determines whether the script should be fetched only after the HTML has been parsed. The src attribute must be present, as this only applies to external scripts.

  • integrity

    The integrity attribute contains metadata that a browser can use to verify that hackers have not compromised the external script.

  • nomodule

    The nomodule attribute is a boolean that determines whether to execute the script in browsers that support ES2015 modules. This is used as a fallback to server alternative script should the browser not support modular JavaScript code.

  • referrerpolicy

    The referrerpolicy attribute specifies the referrer information you wish to send with the <script>.

    Values can include:

    • no-referrer
    • no-referrer-when-downgrade
    • origin
    • origin-when-cross-origin
    • same-origin
    • no-referrer-when-downgrade
    • strict-origin-when-cross-origin
    • unsafe-url
  • src

    The src attribute specifies the URL of an external script.

  • type

    The type attribute specifies the media type of the script.

    Values can include:

    • JavaScript MIME type (default), such as text/javascript or application/javascript.
    • module which indicates a JavaScript module.
    • Any other value is treated as a data block and is not processed.

Best Practices

  • You may want to consider users who cannot run JavaScript in the browser, either because it is disabled or because of lack of support. There is a <noscript> element that can display content in such circumstances. For example:
    <noscript>JavaScript is off. Please enable to view t full site.</noscript>
  • There are several ways to execute JavaScript on the page: async, defer, and immediately (default). It is best to fetch your script using async for performance reasons, or if the script is not required until after the page has loaded, defer.

Specification

Browser Support

Desktop

ChromeEdgeFirefoxIEOperaSafari
YesYesYesYesYesYes

Mobile

Android WebviewChrome AndroidFirefox AndroidOpera AndroidiOS SafariSamsung Internet
YesYesYesYesYesYes