JavaScript Where To
JavaScript code is placed inside <script> tags, or in a separate .js file.
The script Tag
In HTML, JavaScript code goes between <script> and </script>.
Example
<!DOCTYPE html>
<html>
<body>
<h2>Welcome</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "This text was written by JavaScript.";
</script>
</body>
</html>Try it Yourself »You can have as many <script> tags in a page as you like.
Script in the head or the body
A script can go in the <head> or in the <body>. If the script uses an element, that element must already exist when the script runs. A script in the <head> runs before the body is read, so it usually puts its code in a function that is called later, for example on a button click.
Example
<!DOCTYPE html>
<html>
<head>
<script>
function showTime() {
document.getElementById("clock").innerHTML = "Button clicked at " + new Date().toLocaleTimeString();
}
</script>
</head>
<body>
<p id="clock">Click the button.</p>
<button onclick="showTime()">Show time</button>
</body>
</html>Try it Yourself »A simple habit: put your scripts at the end of the body, just before </body>. The page content loads first, so visitors see the page faster and every element exists when the script runs.
External JavaScript
For real websites, write JavaScript in its own file with the .js extension, for example app.js:
Example
// app.js
function greet() {
document.getElementById("demo").innerHTML = "Hello from an external file!";
}Then link it from the HTML page with the src attribute:
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<button onclick="greet()">Greet</button>
<script src="app.js"></script>
</body>
</html>The external file does not contain <script> tags, only JavaScript code.
Why Use External Files?
- HTML and JavaScript are kept apart, so both are easier to read
- One
.jsfile can be used by many pages - The browser saves (caches) the file, so pages load faster the next time
Ways to Link a File
| Way | Example |
|---|---|
| File in the same folder | <script src="app.js"></script> |
| File in a sub folder | <script src="js/app.js"></script> |
| Full URL | <script src="https://example.com/js/app.js"></script> |
The defer Attribute
If you put a script in the <head>, add defer. The browser downloads the file while it reads the page, and runs it only after the whole page is ready.
Example
<head>
<script src="app.js" defer></script>
</head>Exercise
Exercise
What is the correct way to link an external file called main.js?
