MakeW3web

JavaScript in external files

Using JavaScript in external files is a common practice that helps to separate the JavaScript code from the HTML markup, making the code easier to maintain, organize, and reuse. Here's a step-by-step guide on how to use JavaScript in external files:

  1. Create an external JavaScript file:

    • In your text editor or IDE, create a new file with a `.js` extension (e.g., `main.js`). This file will contain your JavaScript code.
  2. Write your JavaScript code:

    • Add your JavaScript code to the external file. For example, you can write a simple function that logs a message to the console:
function showMessage() {
  console.log("Hello, World!");
}
  1. Save the external JavaScript file:

    • Save the `.js` file in the same folder as your HTML file or in a separate folder like `js/` or `scripts/`.
  2. Link the external JavaScript file to your HTML file:

    • In your HTML file, add a `<script>` tag with the `src` attribute pointing to the external JavaScript file. It's best to place this tag right before the closing `</body>` tag to ensure the HTML content is loaded before the script is executed.
<!DOCTYPE html>
<html>
<head>
  <title>External JavaScript Example</title>
</head>
<body>
  <h1>Hello, World!</h1>

  <script src="main.js"></script>
</body>
</html>
  1. Use the JavaScript code in your HTML file:
    • You can now call the functions or use the variables defined in the external JavaScript file from your HTML file. For example, you can add a button to your HTML file that calls the `showMessage` function when clicked:
<!DOCTYPE html>
<html>
<head>
  <title>External JavaScript Example</title>
</head>
<body>
  <h1>Hello, World!</h1>
  <button onclick="showMessage()">Click me!</button>

  <script src="main.js"></script>
</body>
</html>
  1. Test your code:
    • Open the HTML file in your web browser, and the JavaScript code in the external file will be executed. In this example, clicking the button will call the `showMessage` function and log the message to the browser's console.

Using JavaScript in external files has several benefits, including better code organization, separation of concerns, easier code reuse, and improved caching by the browser. It's a best practice to use external JavaScript files when working on any non-trivial web project.

Was this page helpful?