| Introduction to JavaScript :👈 | 👉:JavaScript Variables and Data Types |
Linking JavaScript (JS) to HTML |
Linking JavaScript to HTML
Linking JavaScript (JS) to HTML can be done in three main ways: inline, internal, and external. Each has its own use case depending on the size, complexity, and reusability of your script.
π§· 1. Inline JavaScript
This method embeds JavaScript directly into an HTML element using event attributes like onclick, onmouseover, etc.
β Example:
<!DOCTYPE html>
<html>
<body>
<button onclick="alert('Button clicked!')">Click Me</button>
</body>
</html>
Use case: Quick actions or small scripts tied to specific elements.
π¦ 2. Internal JavaScript
Here, JavaScript is written inside a <script> tag within the HTML file, usually in the <head> or at the end of the <body>.
β Example:
<!DOCTYPE html>
<html>
<head>
<script>
function greet() {
alert('Hello from internal script!');
}
</script>
</head>
<body>
<button onclick="greet()">Greet</button>
</body>
</html>
Use case: Useful for page-specific scripts that donβt need to be reused elsewhere.
π 3. External JavaScript
JavaScript is placed in a separate .js file and linked to the HTML using the src attribute of the <script> tag.
β HTML File:
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<button onclick="sayHi()">Say Hi</button>
</body>
</html>
β script.js File:
function sayHi() {
alert('Hi from external script!');
}
4. Where to place the <script> tag
- At the end of <body> (common): ensures HTML is parsed before script runs.
- In <head> with
defer: downloads early, executes after parsing. - In <head> with
async: downloads and executes as soon as ready (order not guaranteed).
<!-- end of body (simple, reliable) -->
<body>
...content...
<script src="script.js"></script>
</body>
<!-- head with defer (executes after parsing, preserves order) -->
<head>
<script defer src="script.js"></script>
</head>
<!-- head with async (executes when ready, may be out-of-order) -->
<head>
<script async src="analytics.js"></script>
</head>
5. <script type="module">
Use ES modules in the browser. Modules are deferred by default and support import/export.
<script type="module" src="app.js"></script>
/* app.js */
import { greet } from './utils.js';
greet('Alice');
/* utils.js */
export function greet(name) {
console.log(`Hello, ${name}`);
}
6. DOMContentLoaded and safe DOM access
If your script runs before the DOM is ready, wrap code in a DOM ready handler:
document.addEventListener('DOMContentLoaded', function() {
const btn = document.getElementById('myBtn');
if (btn) {
btn.addEventListener('click', () => alert('Clicked'));
}
});
7. Best Practices
- Keep JavaScript in external files for caching and separation of concerns.
- Use
deferfor scripts that depend on DOM elements. - Use
asyncfor independent scripts (analytics, trackers). - Avoid inline event handlers (like
onclick) β prefer addEventListener. - For modern code, use
type="module"and ES module syntax.
8. Small Example: index.html + script.js
<!-- index.html -->
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<h1 id="title">Hello</h1>
<button id="myBtn">Click</button>
<script src="script.js"></script>
</body>
</html>
/* script.js */
const title = document.getElementById('title');
const btn = document.getElementById('myBtn');
btn.addEventListener('click', () => {
title.textContent = 'Button clicked!';
});
Save the files and open index.html in a browser to test.
Use case: Best for large projects, reusable code, and cleaner HTML structure.
π§ Summary Table
| Method | Location | Reusability | Best For |
|---|---|---|---|
| Inline | Inside HTML tags | β No | Quick, one-off actions |
| Internal | <script> tag | β οΈ Limited | Page-specific logic |
| External | Separate .js | β Yes | Modular, scalable applications |
π Mini Project: Hello User
This project will ask the user for their name using prompt() and then display a personalized greeting on the webpage.
β Example Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello User</title>
<script>
function sayHello() {
var userName = prompt("What is your name?");
if (userName) {
document.getElementById("greeting").textContent = "Hello, " + userName + "!";
}
}
</script>
</head>
<body onload="sayHello()">
<h2 id="greeting"></h2>
</body>
</html>
π― How it Works:
- The
sayHello()function runs when the page loads. - It uses
prompt()to ask the user for their name. - If the user enters a name, the script updates the
<h2 id="greeting">element with a personalized message.
Try saving this code in an index.html file and open it in your browser.
| Introduction to JavaScript :👈 | 👉:JavaScript Variables and Data Types |