how to link a javascript file to html

To link a JavaScript file to an HTML document, you can use the <script> tag. Here’s the step-by-step process:

  1. Create a JavaScript file: Save your JavaScript code in a separate file with a .js extension. For example, you can create a file named script.js.
  2. Place the JavaScript file in the appropriate location: Make sure your JavaScript file is located in the same directory as your HTML file, or provide the correct relative or absolute path to the file.
  3. Link the JavaScript file in your HTML: Open your HTML file in a text editor or an HTML editor of your choice. In the <head> section or just before the closing </body> tag, add the following <script> tag:
<script src="path/to/your/script.js"></script>

Replace "path/to/your/script.js" with the correct path to your JavaScript file.

  1. Save and open the HTML file: Save your HTML file with the changes, and then open it in a web browser. The browser will load the HTML file and automatically execute the JavaScript code from the linked JavaScript file.

Make sure to include the JavaScript file after the <body> tag or use the defer attribute if you want the script to load after the HTML content has finished loading. For example:

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

Using the defer attribute ensures that the HTML content is parsed and rendered before the JavaScript is executed.

That’s it! Your JavaScript file is now linked to your HTML file, and the code will be executed when the HTML page is loaded in the browser.