Skip to content

How to include external JavaScript in HTML

  • by

To include an external JavaScript file in an HTML document, you can use the <script> tag in the <head> or <body> section of your HTML document, with the src attribute pointing to the location of your JavaScript file.

You can either specify an absolute URL or a relative URL to the location of the JavaScript file. Additionally, you can use the defer or async attributes to control when the JavaScript code is executed.

<script src="path/to/your/javascript/file.js"></script>

By including external JavaScript files in your HTML document, you can separate your code into separate files, which can make it easier to manage and maintain your code.

Include external JavaScript in the HTML example

To include an external JavaScript file in an HTML document, you can use the following steps:

1. First, create a new file with a .js extension and write the JavaScript code you want to include in your HTML document.

2. Save the file in a folder on your web server or locally on your computer.

3. In your HTML file, add a <script> tag in the <head> section of your document, with the src attribute pointing to the location of your JavaScript file. For example:

<head>
  <script src="path/to/your/javascript/file.js"></script>
</head>

Replace path/to/your/javascript/file.js with the actual path to your JavaScript file.

You can also place the <script> tag at the end of the <body> section of your document, just before the closing </body> tag, to ensure that the JavaScript code is loaded after the HTML content has finished loading. This is known as “deferred loading”.

<body>
  <!-- Your HTML content here -->
  <script src="path/to/your/javascript/file.js" defer></script>
</body>

Here’s an example of a complete HTML document that includes an external JavaScript file:

HTML file (code.html):

<!DOCTYPE html>
<html>
  <head>
    <title>My Page</title>
    <script src="script.js"></script>
  </head>
  <body>
    <h1>Hello, world!</h1>
    <p>This is my page.</p>
    <button onclick="showAlert()">Click me</button>
  </body>
</html>

JavaScript file (script.js):

function showAlert() {
  alert("Hello, world!");
}

Output: In this example, the code.html file and the script.js file are located in the same folder.

How to include external JavaScript in HTML

Do comment if you have any doubts or suggestions on this HTML JS topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *