Skip to content

How to add JavaScript file in HTML

  • by

It’s easy to add JavaScript files in HTML. Here you’ll learn how to create a new JavaScript fileRead JSON file JavaScript, write your JavaScript code, and add the JavaScript file to your HTML page. This guide also covers additional things to keep in mind when adding JavaScript files to HTML

  1. Create or locate the JavaScript file you want to include. It should have a .js file extension.
  2. Place the JavaScript file in a suitable location within your project directory.
  3. Open the HTML file where you want to include the JavaScript code using a text editor.
  4. Inside the <head> or <body> section of your HTML file, add a <script> tag.
  5. Set the src attribute of the <script> tag to the file path or URL of your JavaScript file.

Add JavaScript file in HTML example

Simple example code.

HTML file code

<!DOCTYPE html>
<html>
<head>
  <title>My HTML Page</title>
  <script src="myscript.js"></script>
</head>
<body>
  <h1>This is my HTML page</h1>
</body>
</html>

JS file code

function myFunction() {
  alert("Hello World!");
}

Output:

How to add JavaScript file in HTML

When this code is executed, it will display an alert box with the text “Hello World!”.

Here are some additional things to keep in mind when adding JavaScript files in HTML:

  • You can add multiple JavaScript files to your HTML page.
  • You can place JavaScript files in the <head> or <body> section of your HTML page.
  • If you place JavaScript files in the <head> section, they will be loaded before the rest of the page content.
  • If you place JavaScript files in the <body> section, they will be loaded after the rest of the page content.
  • You can also add inline JavaScript code to your HTML page. Inline JavaScript code is placed between the <script> and </script> tags in the <body> section of your HTML page.

Comment if you have any doubts or suggestions on this Js HTML 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 *