How to Link an External JavaScript File

A separate .js file keeps JavaScript out of your HTML and makes it easier to reuse and debug. This practical tutorial connects index.html to script.js and checks that the path works.

For the core language concepts, read the JavaScript explanation and explore the JavaScript code examples on Playcode123.com.

Create the project files

my-project/
├── index.html
└── script.js

Step 1: write the HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>External JavaScript File</title>
  <script src="script.js" defer></script>
</head>
<body>
  <h1>Coding task</h1>
  <button id="taskButton">Show task</button>
  <p id="task"></p>
</body>
</html>

The src attribute points to the JavaScript file. defer tells the browser to wait until the HTML has been read before running the script.

Step 2: write the JavaScript

Open script.js. Do not add <script> tags to this file.

const taskButton = document.getElementById("taskButton");
const task = document.getElementById("task");

taskButton.addEventListener("click", function () {
  task.textContent = "Change one line of code and test it.";
});

Expected result

The page shows a button. Clicking it displays the coding task below the button. This confirms that the browser loaded and ran script.js.

Using a scripts folder

my-project/
├── index.html
└── js/
    └── script.js

When the JavaScript file is inside the js folder, update the HTML path:

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

Common mistakes

  • Wrong path: the src value must match the real folder structure.
  • Wrong capitalization: script.js and Script.js may be different files on a web server.
  • Hidden file extension: make sure the file is not named script.js.txt.
  • Script tags in the .js file: external files contain JavaScript only.
  • Missing defer: without defer, a script in the head may run before the HTML elements exist.
  • Unsaved files or cached code: save both files and use a hard refresh if necessary.

How to test the connection

Add this temporary first line to script.js:

console.log("script.js is connected");

Open the browser developer tools and select Console. If the message appears after a refresh, the file is connected. Remove the temporary line when you no longer need it.

Exercise

Move script.js into a folder named js and repair the path. Then add a second button that clears the message. Keep both button behaviors in the same external file.

Final check: verify the filename, folder path, defer attribute, element IDs, and browser console.