HTML <script> Tag โ Adding JavaScript
๐ Introduction
The <script> tag is used to add JavaScript to your HTML page.
JavaScript makes your website interactive, allowing you to:
- Handle user actions (clicks, inputs)
- Modify content dynamically
- Create animations and logic
๐งฑ Basic Syntax
1. Internal JavaScript
<script>
// JavaScript code here
</script>
2. External JavaScript
<script src="app.js"></script>
โ Loads JavaScript from another file
๐ก Example (Internal)
<!DOCTYPE html>
<html>
<head>
<title>Script Example</title>
</head>
<body>
<h1 id="title">Hello</h1>
<script>
document.getElementById("title").innerText = "Hello, anyName!";
</script>
</body>
</html>
๐ฅ๏ธ Output Explanation
- The page initially has: Hello
- JavaScript changes it to: Hello, anyName!
๐ก Example (External)
HTML file:
<script src="app.js"></script>
app.js file:
alert("Welcome to my website!");
โ Shows a popup when the page loads
๐ฏ Where to Place <script>
Option 1: Inside <head>
<head>
<script src="app.js"></script>
</head>
โ ๏ธ May load before the page content
Option 2: Before </body> (Recommended)
<body>
<h1>Hello</h1>
<script src="app.js"></script>
</body>
โ Ensures HTML loads first โ Better performance
โก Using defer
<script src="app.js" defer></script>
โ Loads script in background โ Runs after HTML is parsed
๐ฏ Common Use Cases
- Handling button clicks
- Form validation
- Dynamic content updates
- API calls
โ ๏ธ Tips & Best Practices
- Prefer external JavaScript files
- Place scripts before
</body>or usedefer - Keep JavaScript separate from HTML for clean code
๐ซ Common Mistakes
- Forgetting
srcpath โ - Placing script too early (before elements exist) โ
- Mixing too much JS inside HTML โ
๐งช Mini Exercise
- Create a button:
<button onclick="showMessage()">Click me</button>
- Add script:
<script>
function showMessage() {
alert("Hello!");
}
</script>
๐ Click the button and see what happens