Skip to content

Where To (Script Tag)

In HTML, JavaScript code is inserted between <script> and </script> tags.

1. Internal JavaScript

You can write JavaScript directly in your HTML file.

<!DOCTYPE html>
<html>
<body>
  <h2>Internal Script</h2>
  <p id="demo"></p>

  <script>
    document.getElementById("demo").innerHTML = "Hello from Internal JS!";
  </script>
</body>
</html>

2. External JavaScript

Scripts can also be placed in external files. External files often contain code to be used in several different web pages. - File extension: .js - Benefit: Keeps code organized and allows browsers to cache the script for better performance.

script.js

function myFunction() {
  document.getElementById("demo").innerHTML = "Hello from External File!";
}

index.html

<script src="script.js"></script>

Script Placement

You can place the <script> tag in the <head> or at the bottom of the <body>.

Placing scripts at the bottom of the <body> element improves display speed, because script interpretation slows down the display.

async and defer

Modern HTML allows async and defer attributes on external scripts. defer tells the browser to download the script in the parallel but only execute it after the HTML parsing is complete.


← Back: Intro | Next: Output →