HTML Tags
HTML <script> Tag
The <script> tag is used to embed or reference executable JavaScript in an HTML document.
What is the <script> tag?
The <script> element either contains inline JavaScript or links to an external script file through its src attribute. Scripts can be placed in the <head> or <body>; by default they block parsing while they load and run, which is why loading strategy matters.
Syntax
<!-- Inline -->
<script>
console.log("Hello from inline script");
</script>
<!-- External -->
<script src="app.js" defer></script>Complete example
<!DOCTYPE html>
<html lang="en">
<body>
<button id="btn">Click me</button>
<script>
const btn = document.getElementById("btn");
btn.addEventListener("click", () => {
alert("Button clicked!");
});
</script>
</body>
</html>Attributes
| Attribute | Description |
|---|---|
| src | URL of an external script file. When present, the element must be empty. |
| type | Script type. Use type="module" for ES modules; text/javascript is the default and can be omitted. |
| async | For external scripts, downloads in parallel and runs as soon as ready, without preserving order. |
| defer | For external scripts, downloads in parallel but runs in order after the document is parsed. |
| crossorigin | Configures CORS handling for the fetched script. |
| nonce | A cryptographic nonce allowing the script under a Content Security Policy. |
💡
async and defer only apply to external scripts (those with src). For most cases, defer is the safest choice because it keeps execution order and does not block parsing.
The <script> tag is supported in all browsers. Modules (type="module") are deferred by default and are widely supported in modern browsers.
