HTML Tags
HTML <script> Tag
The <script> tag is used to embed or reference executable code, most commonly JavaScript. It can hold inline code or load an external file via the src attribute.
The <script> Tag
The <script> element either contains inline JavaScript between its tags or loads an external script through the src attribute. Scripts let you add interactivity, respond to events, and manipulate the page dynamically.
Scripts can appear in <head> or <body>. Placing them at the end of <body>, or using defer, prevents them from blocking the initial rendering of the page.
Syntax
<!-- Inline -->
<script>
console.log("Hello");
</script>
<!-- External -->
<script src="app.js"></script>Example
<!DOCTYPE html>
<html>
<body>
<h1 id="greeting">Loading...</h1>
<button onclick="changeText()">Click me</button>
<script>
function changeText() {
document.getElementById("greeting").textContent = "Button clicked!";
}
document.getElementById("greeting").textContent = "Ready";
</script>
</body>
</html>More Examples
<!DOCTYPE html>
<html>
<body>
<p id="time"></p>
<script>
const now = new Date().toLocaleTimeString();
document.getElementById("time").textContent = "Page loaded at " + now;
</script>
</body>
</html>Attributes
| Attribute | Description |
|---|---|
| src | URL of an external script file to load. |
| type | Script type; use module for ES modules. Defaults to JavaScript. |
| async | Download in parallel and run as soon as ready (external scripts). |
| defer | Download in parallel but run after the document is parsed. |
| crossorigin | Controls CORS behaviour when fetching an external script. |
Use defer or place scripts at the end of the body so they do not block page rendering. Use async for independent scripts like analytics.
Key Takeaways
- <script> holds inline JavaScript or loads an external file with src.
- It can go in the head or body.
- defer runs the script after parsing; async runs it as soon as it loads.
- type="module" enables ES modules.
- Placing scripts before </body> avoids blocking rendering.
