<htmlstart/>

HTML and JavaScript

Use the <script> tag to add JavaScript to your HTML pages.

The <script> Tag

JavaScript is added with the <script> tag. You can write JS directly inside it, or link an external file.

Inline Script

<button onclick="sayHello()">Click me</button>

<script>
function sayHello() {
  alert("Hello, World!");
}
</script>

External Script (Recommended)

<!-- At the bottom of <body>, before </body> -->
<script src="app.js"></script>

Common JS + HTML Interactions

<!-- Change text -->
<h1 id="title">Hello</h1>
<button onclick="document.getElementById('title').textContent = 'World!'">
  Change heading
</button>

<!-- Hide/show an element -->
<div id="box" style="display:block;">I can hide!</div>
<button onclick="document.getElementById('box').style.display = 'none'">
  Hide the box
</button>

Where to Place Scripts

PositionEffect
In <head>Blocks page render — avoid for large scripts
End of <body>Page loads first, then JS — recommended
defer attributeDownloads in background, runs after HTML parsed
<!-- Best practice: defer in head -->
<script src="app.js" defer></script>
Use defer on external scripts in <head> — it downloads in the background without blocking HTML parsing and runs after the DOM is ready.