Loading...
Published on October 4, 2025
HTML + JS
Just like CSS, you can (and most of the time should) keep your JavaScript code in a separate file instead of writing it directly inside your HTML. This makes your code cleaner, easier to manage, and reusable. In this guide, we’ll learn how to link a JavaScript file to an HTML page.
/project-folder ├── index.html └── script.js
To link your JavaScript file, use the <script> tag inside your HTML. Here’s a simple example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>My First JavaScript Example</title> </head> <body> <h1>Hello, world!</h1> <button id="myButton">Click Me</button> <!-- Link your JS file here --> <script src="script.js"></script> </body> </html>
It’s placed just before the closing </body> tag. This way, the browser loads all the HTML first before running your JavaScript. If you put it in the <head> without extra settings, the script might try to run before the HTML elements exist, potentially causing errors. You may need to adjust the string passed into the src tag to fit the local location of the file, if you are using a different folder structure than I.
Now, open your script.js file and add some code.
// script.js
const button = document.getElementById("myButton");
button.addEventListener("click", () => {
alert("You clicked the button!");
});
Open your index.html in a browser and click the button. You should see a pop-up message! With this, you are done.
Linking an external JavaScript file is as simple as using the <script> tag. By keeping your code in a separate .js file, you’ll make your projects cleaner, easier to maintain, and more professional.