📝 Writing JavaScript in HTML using <script> Tag
JavaScript is typically embedded into HTML pages using the <script> tag. You can place the script directly in your HTML file or link to an external JavaScript file.
🔹 Method 1: Inline JavaScript
Write JavaScript directly within your HTML file using the <script> tag.
<!DOCTYPE html>
<html>
<head>
<title>Inline JS Example</title>
</head>
<body>
<h1>Hello!</h1>
<script>
alert("This is inline JavaScript!");
</script>
</body>
</html>
🔹 Method 2: JavaScript in <head> vs <body>
- In <head>: Script runs before page content is loaded (can delay rendering).
- At the end of <body>: Recommended — script runs after content is loaded.
🔹 Method 3: External JavaScript File
Use the src attribute to link to a separate .js file:
<!DOCTYPE html>
<html>
<head>
<title>External JS</title>
</head>
<body>
<h1>External JavaScript Example</h1>
<script src="script.js"></script>
</body>
</html>
Note: The script.js file must be in the same folder or provide a correct path.
✅ Best Practices:
- Place scripts just before
</body>for better page load speed. - Use external files to keep HTML clean and JavaScript reusable.
- Avoid mixing inline JavaScript and HTML unless necessary (e.g., learning or small demos).


