JavaScript Where To

There are several places you can put JavaScript in a web page, and choosing the right one keeps your code organized and fast.

The <script> Tag

JavaScript is added to an HTML document with the <script> tag. Any code you place between an opening <script> and closing </script> tag will be executed by the browser when it reaches that point in the page. You can include as many script blocks as you like, and you can place them in either the head or the body of the document.

Example

<!DOCTYPE html>
<html>
<body>

<h2>The script Tag</h2>
<p id="demo">Original text</p>

<script>
  document.getElementById('demo').innerHTML = 'Hello from a script tag!';
</script>

</body>
</html>

Internal JavaScript: Head vs Body

Code written directly inside the HTML file is called internal JavaScript. You can put the <script> tag in the <head> section or in the <body> section. Where you place it matters, because the browser reads an HTML page from top to bottom. A script that tries to change an element before that element exists on the page will fail.

  • Placing a script in the <head> keeps it separate from the visible content, but it runs before the body has loaded.
  • Placing a script at the end of the <body> is a common practice, because by then all page elements are available for the code to use.
  • You can mix both approaches, but keeping scripts near the end of the body avoids many beginner errors.

Example

<!DOCTYPE html>
<html>
<body>
  <h1>My Page</h1>
  <p id="demo">Original text</p>

  <!-- Script at the end can safely use elements above it -->
  <script>
    document.getElementById('demo').innerHTML = 'Text updated!';
  </script>
</body>
</html>

External JavaScript

For anything beyond a few lines, it is best to move your JavaScript into a separate file with a .js extension and link to it. This is called external JavaScript. You reference the file using the src attribute of the <script> tag, and the same file can be shared across many HTML pages.

Example

<!DOCTYPE html>
<html>
<body>

<h2>External JavaScript</h2>

<script src="app.js"></script>

<script>
  // The code below would normally live in its own file named app.js
  console.log('This code lives in a separate file.');
</script>

</body>
</html>
Note: Keeping JavaScript in external files makes your code easier to read, lets browsers cache the file so pages load faster on repeat visits, and allows you to reuse the same logic on multiple pages.

Comparing the Options

PlacementBest used when
Internal in <head>Short setup code that must run before the page renders
Internal at end of <body>Small scripts that manipulate elements already on the page
External .js fileAny real project, shared or reusable code, and larger scripts
Note: You can add multiple external files to a single page. They run in the order they appear in the HTML, so list them in the sequence your code depends on.

Exercise: JavaScript Where To

Which HTML tag is used to embed or reference JavaScript?