Menu Close

How to Link JavaScript File in HTML ?

Posted in Javascript Tutorial

To link a JavaScript file in an HTML document, you can use the <script> element. Here’s how you can do it:

  1. Create a JavaScript File: First, you need to create a JavaScript file with a “.js” extension. For example, you can create a file called “myscript.js” and add your JavaScript code to it.
  2. Place the Script Tag in HTML: In your HTML document, you should include the following line within the <head> section or just before the closing </body> tag. You can use either of the following approaches:a. Inside the <head> section:
<head>
   <script src="myscript.js"></script>
</head>

b. Just before the closing tag:

<body>
   <!-- Your HTML content here -->
   <script src="myscript.js"></script>
</body>

Placing the <script> tag just before the closing </body> tag is a common practice because it allows the HTML content to load first, making your web page appear more responsive to users.

   3. Specify the “src” Attribute: In the <script> element, use the “src” attribute to specify the path to your JavaScript file. This path can be either a relative or absolute URL to the JavaScript file. In the examples above, “myscript.js” is a relative URL, assuming the JavaScript file is in the same directory as the HTML file. If your JavaScript file is in a different directory, you should specify the correct path.

Here’s a complete example:

<!DOCTYPE html>
<html>
<head>
   <title>My Web Page</title>
   <script src="myscript.js"></script>
</head>
<body>
   <!-- Your HTML content here -->
</body>
</html>

By linking your JavaScript file using the <script> element, you can keep your HTML and JavaScript code separate, which is a good practice for maintaining clean and organized code.

Example 1

<!DOCTYPE html>
<html lang="en">
  
<head>
    <title>
        Basic Example to Describe JavaScript
    </title>
</head>
  
<body>
  
    <!-- JavaScript code can be embedded inside
        head section or body section -->
    <script>
        console.log("Welcome to ICSTutorial");
    </script>
</body>
  
</html>

Results:

Welcome to ICSTutorial

Leave a Reply