🧠 HTML <script>
Tag — Embedding or Linking JavaScript in Web Pages
The <script>
tag in HTML is used to embed JavaScript code or reference external JavaScript files. It allows developers to make web pages dynamic, interactive, and responsive to user behavior.
📌 What Is the <script>
Tag?
- The
<script>
tag is an HTML element used to define client-side scripts. - It can contain inline code or link to external files.
- Scripts can be placed in the
<head>
or<body>
, though best practice is to load them just before the closing</body>
tag.
✅ Basic Syntax
1. Inline JavaScript
<script>
alert("Hello, world!");
</script>
2. External JavaScript File
htmlCopyEdit<script src="script.js"></script>
🧪 Example 1: Simple Inline Script
<!DOCTYPE html>
<html>
<head>
<title>Script Example</title>
</head>
<body>
<h1>Welcome!</h1>
<script>
console.log("Page has loaded.");
</script>
</body>
</html>
🧪 Example 2: Linking External JavaScript
htmlCopyEdit<script src="app.js"></script>
Contents of app.js
:
document.body.style.backgroundColor = "#f0f8ff";
⚙️ Attributes of <script>
Attribute | Description |
---|---|
src | URL of external script file |
type | MIME type (usually text/javascript ; often omitted) |
async | Loads script asynchronously (executes as soon as ready) |
defer | Defers script execution until after HTML is parsed |
nomodule | Prevents execution in modern browsers (used with type="module" ) |
🔁 async
vs defer
Attribute | Load Order | Execution Timing |
---|---|---|
async | As soon as available | Immediately (can interrupt parsing) |
defer | In order of appearance | After parsing HTML (safe for DOM) |
Example:
<script src="main.js" defer></script>
🧩 Modern JavaScript Modules
Use type="module"
to load ES6 modules:
<script type="module" src="main.js"></script>
This supports import
and export
syntax and enables modular JavaScript development.
⚠️ Security Note: Avoid Inline Scripts When Possible
Using inline scripts makes your site more vulnerable to cross-site scripting (XSS). For better security:
- Use external files
- Set appropriate
Content-Security-Policy
headers
🎨 Styling Example: Dynamic DOM Manipulation
<script>
document.querySelector("h1").style.color = "tomato";
</script>
Changes the color of the <h1>
text on page load.
💡 When to Use <script>
Use Case | Example |
---|---|
Add interactivity | Button clicks, animations |
Load external APIs | Google Maps, Stripe, etc. |
Dynamic content updates | DOM changes, live data |
Analytics or tracking | Google Analytics, Matomo, etc. |
🏁 Summary
The <script>
tag is essential for adding logic and interactivity to web pages using JavaScript. Use it wisely with modular code, defer/async, and external files for better performance, security, and maintainability.