HTML provides the structure of web pages, while JavaScript adds dynamic logic, event handling, DOM manipulation, and interactive features. You integrate JavaScript into HTML using the <script> tag.
JavaScript can be written inline inside <script> blocks or loaded from external .js files.
<!-- Inline JavaScript block -->
<script>
console.log("Page loaded successfully!");
</script>
<!-- External JavaScript file with async defer attributes -->
<script src="app.js" defer></script>
Script loading options explained:
defer Attribute: Downloads the script in the background while HTML parses, executing only after DOM parsing finishes (recommended for app scripts).async Attribute: Downloads in the background and executes immediately as soon as ready (best for independent analytics scripts).flowchart TD
A["Script Loading Strategy"] --> B["Default: Blocks HTML parsing while loading"]
A --> C["defer: Parses HTML first, runs script when ready (Recommended)"]
A --> D["async: Loads asynchronously, pauses parsing when executing"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML JavaScript Integration Demo</title>
</head>
<body style="font-family: system-ui, sans-serif; background-color: #0f172a; color: #f8fafc; padding: 2rem;">
<h2>Interactive Counter App</h2>
<div style="background-color: #1e293b; padding: 1.5rem; border-radius: 8px; max-width: 400px;">
<p style="font-size: 1.25rem;">Count: <span id="counter-value" style="color: #38bdf8; font-weight: bold;">0</span></p>
<button id="increment-btn" style="background-color: #2563eb; color: #ffffff; padding: 10px 16px; border: none; border-radius: 6px; cursor: pointer;">
Increment Counter
</button>
</div>
<!-- Script placed before closing body tag -->
<script>
let count = 0;
const countDisplay = document.getElementById('counter-value');
const button = document.getElementById('increment-btn');
button.addEventListener('click', () => {
count++;
countDisplay.textContent = count;
});
</script>
</body>
</html>
defer: Keep JavaScript code organized in separate .js files loaded with defer in <head> for optimal page speed.<body> if not using defer: Ensures visual HTML elements render on screen before scripts run.onclick="..." attributes inside HTML tags. Attach event listeners in JS files using addEventListener().Create a button with id="theme-btn" and write a <script> block that toggles the document body background color when clicked!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.