JavaScript is added to a page with the <script> tag.
Internal script
Write code between <script> and </script>, usually at the end of the <body>.
External file (best)
Save code in a .js file and link it:
<script src="app.js" defer></script>
One file can be used on many pages, and the browser can cache it.
Head or body?
- Scripts at the end of body run after the HTML is loaded.
- Scripts in the head need the
deferattribute, so they wait until the page is ready.
The external file must not contain <script> tags — only JavaScript code.
Example
Example — Script at the end of body
HTML
<!DOCTYPE html>
<html>
<body>
<h2>My Page</h2>
<p id="demo"></p>
<script>
document.getElementById('demo').textContent = 'This text was added by JavaScript.';
</script>
</body>
</html>