HTML <script> Tag

The <script> tag in HTML is used to embed or reference executable scripts, most commonly JavaScript, within an HTML document. It allows developers to add dynamic behavior, handle user interactions, and manipulate the Document Object Model (DOM) of a webpage, significantly enhancing the user experience.

HTML Script Tag: Adding JavaScript to Your Web Pages

Syntax

<script 
  src="url"
  type="text/javascript|module"
  async
  defer
  crossorigin="anonymous|use-credentials"
  integrity="hash-value"
  referrerpolicy="no-referrer|no-referrer-when-downgrade|origin|origin-when-cross-origin|same-origin|strict-origin|strict-origin-when-cross-origin|unsafe-url"
>
  // Inline script code goes here
</script>

Attributes

Attribute Value Description
src URL Specifies the URL of an external script file. If this attribute is present, the content inside the <script> tag is ignored.
type text/javascript \ module Defines the script's type. The default is text/javascript. Using module indicates that the script is a JavaScript module, enabling ES modules features like imports and exports.
async async Indicates that the script should be executed asynchronously as soon as it's available without blocking HTML parsing. Use this for non-essential scripts.
defer defer Indicates that the script should be executed after the HTML document has been fully parsed, but before the DOMContentLoaded event. This is ideal for scripts that rely on the DOM structure.
crossorigin anonymous \ use-credentials Enables CORS requests for scripts loaded via src. anonymous sends no credentials, while use-credentials sends cookies and authorization headers. Use only when necessary for cross-origin scripts.
integrity hash-value (e.g., sha384-abcdefg...) Provides a cryptographic hash of the script's content, allowing browsers to verify the script's integrity. Prevents the browser from executing modified or malicious scripts.
referrerpolicy no-referrer \ no-referrer-when-downgrade \ origin \ origin-when-cross-origin \ same-origin \ strict-origin \ strict-origin-when-cross-origin \ unsafe-url Specifies the referrer policy to use when fetching the script. This dictates which referrer information (if any) is included in the request header. Consult the documentation for precise security implications of each value.

Example

This is the most basic example of an inline <script> tag that displays an alert.

<!DOCTYPE html>
<html>
<head>
  <title>Basic Script Example</title>
</head>
<body>
  <script>
    alert("Hello from JavaScript!");
  </script>
</body>
</html>

More Examples

Example 1: External Script

This example demonstrates linking to an external JavaScript file.

myScript.js:

console.log("This message is from myScript.js");

index.html:

<!DOCTYPE html>
<html>
<head>
  <title>External Script Example</title>
</head>
<body>
  <script src="myScript.js"></script>
</body>
</html>

Example 2: Defer Attribute

Here's how you use the defer attribute to ensure the script runs after the page has been fully parsed, but before it's ready for user interaction.

<!DOCTYPE html>
<html>
<head>
  <title>Defer Script Example</title>
</head>
<body>
  <p id="myParagraph">This is a paragraph.</p>
  <script src="deferScript.js" defer></script>
</body>
</html>

deferScript.js

document.getElementById('myParagraph').textContent = 'Paragraph updated by script.';

Example 3: Async Attribute

Using async allows the script to execute as soon as it's available, without blocking HTML parsing. Useful for independent scripts like analytics.

<!DOCTYPE html>
<html>
<head>
  <title>Async Script Example</title>
</head>
<body>
  <script src="asyncScript.js" async></script>
</body>
</html>

asyncScript.js:

console.log("Async script executed.");

Example 4: Module Script

Illustrates how to use module script to import functionalities:

myModule.js

export function greet(name) {
    console.log(`Hello, ${name}!`);
}

index.html:

<!DOCTYPE html>
<html>
<head>
  <title>Module Script Example</title>
</head>
<body>
    <script type="module">
        import { greet } from './myModule.js';
        greet('User');
    </script>
</body>
</html>

Browser Support

The <script> tag is supported by all modern browsers. However, ensure you test your scripts for proper functionality across different browser versions and devices.

Feature Chrome Edge Firefox Safari Opera
<script> Yes Yes Yes Yes Yes
async Yes Yes Yes Yes Yes
defer Yes Yes Yes Yes Yes
module Yes Yes Yes Yes Yes
crossorigin Yes Yes Yes Yes Yes
integrity Yes Yes Yes Yes Yes
referrerpolicy Yes Yes Yes Yes Yes

Notes and Tips

  • Place <script> tags right before the closing </body> tag or use async or defer for better page load performance.
  • Use external JavaScript files (src attribute) for better code organization and caching.
  • Avoid writing large amounts of JavaScript code directly inside the <script> tag.
  • Always validate your JavaScript code for errors to avoid unexpected behaviors.
  • Use module script for modern JavaScript development practices.
  • Use the integrity attribute with a cryptographic hash of external scripts to ensure that the scripts you are loading haven't been tampered with. This is a key security measure.
  • Use referrerpolicy to set the referrer headers when loading a script via the src attribute and keep security in mind.
  • Understand the difference between async and defer for proper script execution order and avoiding layout shifts.