JavaScript Where To

script tags, external files and placement.

✍️ 3 exercises + code challenge in this lesson

JavaScript code is placed in a <script> element. It can go in the <head>, in the <body>, or in an external file.

External JavaScript

<script src="app.js"></script> loads code from a separate file. This keeps HTML and JavaScript apart, and browsers can cache the file.

Place scripts at the end of the <body>, or use <script src="app.js" defer> in the head, so the HTML loads first.

Key Takeaways: JavaScript Where To

Mastering JavaScript Where To helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

JavaScript Where To Code Example

JavaScript
<!DOCTYPE html>
<html>
<head>
  <script>
    function greet() {
      document.getElementById("msg").innerHTML = "Function defined in the head.";
    }
  </script>
</head>
<body>
  <p id="msg">Click the button.</p>
  <button onclick="greet()">Try it</button>

  <script>
    // Code at the end of the body runs after the HTML above exists
    document.body.style.fontFamily = "Arial";
  </script>
</body>
</html>
Free sign-in required · Google login available

JavaScript Where To Practice Exercises

Check what you learned in “JavaScript Where To”.

/ 3 solved
Fill in the blank

Load JavaScript from an external file.

<script ="app.js"></script>
✓ Correct! Not quite. Try again.
Multiple choice

Which attribute makes an external script run after the HTML has loaded?

✓ Correct! Not quite. Try again.
Code challenge

Add a <script> that sets the page background to "lightyellow".

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services