Loading lessons...
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:
html
<script>
document.getElementById("demo").innerHTML = "Hello!";
</script>
2. In an external file
Write JavaScript in a .js file and link it:
html
<script src="myscript.js"></script>
This is the recommended way. It keeps code organized and reusable across pages.
3. In HTML attributes (avoid)
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 </body> so the page renders first, which is common practice.
The .js file extension
External files use the .js extension and contain only JavaScript, no <script> tags.
TL;DR
- JavaScript goes inside
<script>tags or external.jsfiles. - External files are linked with
<script src="...">. - Put scripts before
</body>so the page loads fast. - External files are the cleanest, most reusable approach.