Adding JavaScript to HTML
Learn how to add JavaScript to your web pages — inline, internal, and external scripts.
Adding JavaScript to HTML
JavaScript adds interactivity to your web pages — handling clicks, form submissions, animations, and dynamic content. Let's learn how to add it to HTML.
Method 1: Inline JavaScript
Add JavaScript directly in HTML attributes (event handlers):
<button onclick="alert('Hello!')">Click Me</button>
Pros: Quick for demos
Cons: Not reusable, mixes HTML and JS, hard to maintain
Method 2: Internal JavaScript
Place JavaScript inside a <script> tag in your HTML:
<body>
<h1 id="title">Hello</h1>
<button id="btn">Change Title</button>
<script>
const btn = document.getElementById('btn');
btn.addEventListener('click', function() {
document.getElementById('title').textContent = 'Title Changed!';
});
</script>
</body>
Pros: No extra files needed
Cons: Only applies to one page, mixes concerns
Method 3: External JavaScript (Recommended)
Create a separate .js file and link it:
<!-- In your HTML -->
<body>
<h1 id="title">Hello</h1>
<button id="btn">Change Title</button>
<script src="script.js"></script>
</body>
// script.js
const btn = document.getElementById('btn');
btn.addEventListener('click', function() {
document.getElementById('title').textContent = 'Title Changed!';
});
Where to Place the <script> Tag
| Location | Behavior | Recommendation |
|---|---|---|
In <head> | Runs before body loads — may cause errors if accessing DOM | Use with defer attribute |
End of <body> | Runs after all HTML is loaded | ✅ Recommended default |
The defer and async Attributes
If you must place scripts in the <head>:
<!-- defer: runs AFTER HTML is fully parsed (preserves order) -->
<script src="script.js" defer></script>
<!-- async: runs as soon as downloaded (doesn't preserve order) -->
<script src="analytics.js" async></script>
| Attribute | When It Runs | Best For |
|---|---|---|
defer | After HTML is fully parsed | Main app scripts that need the DOM |
async | As soon as downloaded | Independent scripts (analytics, ads) |
| Neither | Immediately (blocks HTML parsing) | Avoid in <head> |
Key Takeaways
- Three methods: inline, internal, and external JavaScript
- External JS is the recommended approach
- Place
<script>at the end of<body>or usedefer deferwaits for HTML to parse;asyncruns immediately- Use
<script src="file.js"></script>to link external JS