Tag script

🧠 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>

AttributeDescription
srcURL of external script file
typeMIME type (usually text/javascript; often omitted)
asyncLoads script asynchronously (executes as soon as ready)
deferDefers script execution until after HTML is parsed
nomodulePrevents execution in modern browsers (used with type="module")

🔁 async vs defer

AttributeLoad OrderExecution Timing
asyncAs soon as availableImmediately (can interrupt parsing)
deferIn order of appearanceAfter 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 CaseExample
Add interactivityButton clicks, animations
Load external APIsGoogle Maps, Stripe, etc.
Dynamic content updatesDOM changes, live data
Analytics or trackingGoogle Analytics, Matomo, etc.

🏁 Summary

The <script> tag is essential for adding logic and interactivity to web pages using JavaScript. Use it wisely with modular codedefer/async, and external files for better performance, security, and maintainability.