JavaScript Where To
JavaScript code is inserted between tags. You can place scripts in the
, in the , or in an external file.In the <body>
Placing scripts at the bottom of the
element improves the display speed, because script interpretation slows down the display.Example — function called from button
function showMessage() {
console.log("Button clicked!");
}
showMessage();In the <head>
Example — function defined in head
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("World"));External JavaScript
Scripts can be placed in external files. External scripts are referenced with a src attribute:
| Advantage | Why It Helps |
|---|---|
| Separation of concerns | HTML and JS are in separate files |
| Reusability | One script used by many HTML pages |
| Caching | Browser caches the file for faster loads |
| Readability | Cleaner HTML markup |
External script references
// Reference external scripts with src attribute:
// <script src="https://example.com/js/myScript.js"></script>
// <script src="/js/myScript.js"></script>
// <script src="myScript.js"></script>
console.log("External scripts keep HTML clean!");📝 Note: You cannot use both src and inline code in the same