agyanadda@gmail.com

JS Where To

JavaScript Basics 1 min read Updated Dec 1, 2026 Topic 2 of 38

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 defer attribute, 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>

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which attribute links an external JavaScript file?

Exercise 2 True / False

An external .js file must start with a <script> tag.

Exercise 3 Fill in the Blank

The ___ attribute makes a script in the head wait until the HTML is loaded.

Frequently Asked Questions

Both load the file without blocking. defer runs scripts in order after the HTML is parsed; async runs each script as soon as it downloads, in any order.