How to Add JavaScript to a Page
JavaScript Where To
Where to put JavaScript — inline in a `<script>` tag, or in an external `.js` file. And where in the HTML it should go.
What you'll learn
- Add JavaScript to an HTML page with the `<script>` tag
- Link to an external JavaScript file
- Understand where to place `<script>` (head vs body, defer, async)
In HTML, JavaScript code lives inside a <script> tag. The browser
runs the code when it encounters the tag while loading the page.
Inline Script
You can put JavaScript directly inside the HTML:
<!doctype html>
<html>
<body>
<h1>My First Page</h1>
<script>
document.body.innerHTML += "<p>Hello from JavaScript!</p>";
</script>
</body>
</html> This works, but mixing logic and markup gets messy fast. For anything beyond a quick experiment, prefer an external file.
External Script
Put your JavaScript in a separate .js file and link to it from the
HTML:
<!doctype html>
<html>
<body>
<h1>My First Page</h1>
<script src="app.js"></script>
</body>
</html> document.body.innerHTML += "<p>Hello from JavaScript!</p>";
External scripts are easier to read, easier to cache, and easier to share across pages.
Where in the HTML?
The <script> tag can go in the <head> or anywhere in the <body>.
But where you put it changes when it runs — which matters because
your script needs the elements it touches to already exist.
You can also tell the browser how to load the script using the
defer or async attributes:
| Placement | When it runs | Recommended? |
|---|---|---|
<script> in <head> | Blocks parsing, runs immediately | No — slows down the page |
<script> at end of <body> | After the page is parsed | Old pattern, still works |
<script defer> in <head> | After parsing, in order | ✅ Best for most code |
<script async> in <head> | As soon as it downloads, no order guarantee | For independent scripts (analytics) |
<script type="module"> | Deferred by default | ✅ For modern apps |
A Complete Example
A minimal page with an external script that runs after the HTML loads:
<!doctype html>
<html>
<head>
<title>Hello</title>
<script defer src="app.js"></script>
</head>
<body>
<h1 id="greet">…</h1>
</body>
</html>document.getElementById("greet").textContent = "Hello, world!"; Up Next
You can now load JavaScript on a page. Next: how to make it show output.
JavaScript Output →