Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14
Chapter 5

The <script> Tag & Where to Put Scripts

Embedding JavaScript in HTML, script placement, and external files.


The <script> Tag

The HTML <script> tag tells the browser to expect JavaScript between its opening and closing tags.

<html>
<body>
  <script>
    document.write("This is not Java");
  </script>
</body>
</html>
  • Opening <script> tag — signals that the content between the tags is JavaScript, not HTML.
  • document.write() — writes text or HTML directly into the page.

Where to Put Your Scripts

PlacementNotes
In the <head>Loaded before the page body. Best for functions called from HTML elements.
In the <body>Runs when the browser reaches that point. Preferred for DOM manipulation.
In bothYou can split scripts between the two sections.
External .js fileLinked via <script src="...">. Keeps HTML clean, enables caching and reuse.

Scripts in the <head>

<head>
  <script>
    function myFunction() {
      document.getElementById("demo").innerHTML = "Paragraph changed.";
    }
  </script>
</head>

Scripts in the head run before the DOM is rendered. Avoid direct DOM access in the head unless it is inside a function that is called later.

Scripts at the end of <body>

<body>
  <button onclick="myFunction()">Click</button>
  <p id="demo"></p>

  <script>
    function myFunction() {
      document.getElementById("demo").innerHTML = "Paragraph changed.";
    }
  </script>
</body>

Best practice: place scripts at the bottom of <body> so the DOM is fully loaded before your script runs.

External JavaScript Files

<head>
  <script src="myscript.js"></script>
</head>
  • Separation of concerns — HTML handles structure, JavaScript handles behaviour.
  • Easier maintenance — changes to logic are made in one place; many pages can share the file.
  • Browser caching — the file is downloaded only once, speeding up repeat visits.

Activity — complete the code

Complete the code correctly to mark this lesson as complete automatically.

Complete the script embedding and placement.

<!-- External JavaScript file -->
<head>
<script ="myscript.js"></script>
</head>
 
<!-- Inline script -->
<>
document.write("This is not Java");
</script>
 
<!-- Best practice: put scripts at the bottom of -->
<>
...
</body>