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.