Lesson 2 +10 XP

Where to Put JavaScript

There are three main ways to add JavaScript to your web pages.

1. Inside HTML (script tag)

You can write JavaScript between <script> tags:

Code

html
<script>
  document.getElementById("demo").innerHTML = "Hello!";
</script>

2. In an external file

Write JavaScript in a .js file and link it:

Code

html
<script src="myscript.js"></script>

This is the recommended way. It keeps code organized and reusable across pages.

3. In HTML attributes (avoid)

Code

html
<button onclick="myFunction()">Click me</button>

Inline event handlers work but mix JavaScript with HTML, which gets messy.

Where in the page?

  • Put scripts in the head for functions used early.
  • Put scripts just before &lt;/body&gt; so the page renders first, which is common practice.

The .js file extension

External files use the .js extension and contain only JavaScript, no &lt;script&gt; tags.

TL;DR

  • JavaScript goes inside &lt;script&gt; tags or external .js files.
  • External files are linked with &lt;script src=&quot;...&quot;&gt;.
  • Put scripts before &lt;/body&gt; so the page loads fast.
  • External files are the cleanest, most reusable approach.