Linking JavaScript to Html


To make your web pages interactive, you need to connect your JavaScript code to your HTML file. There are three main ways to do this — let’s explore each!



1. Inline JavaScript

You can write JavaScript code directly inside an HTML element using the onclick or other event attributes.

<button onclick="alert('Hello!')">Click Me</button>
  • Pros: Super quick for small interactions.
  • Cons: Not recommended for larger projects — mixes logic with structure.


2. Internal JavaScript (Inside the HTML File)

You can add JavaScript within a <script> tag in your HTML file.

<!DOCTYPE html>
<html>
<head>
  <title>Internal JS</title>
</head>
<body>
  <h1>Hello, World!</h1>

  <script>
    console.log("This is internal JavaScript.");
  </script>
</body>
</html>

  • Pros: Good for small projects or testing.
  • Cons: Still mixes HTML and JavaScript.


3. External JavaScript (Best Practice)

For larger projects, it's best to write JavaScript in a separate .js file and link it using the <script src=""> tag.

Step-by-step:

  • 1. Create a file called script.js
  • Write your JavaScript inside it:

console.log("Hello from external JS!");

3. Link it in your HTML file like this:


<!DOCTYPE html>
<html>
<head>
  <title>External JS</title>
</head>
<body>
  <h1>Welcome</h1>

  <script src="script.js"></script>
</body>
</html>

    Bonus: Using defer or async (Advanced Option)

    You can add these attributes to control when the JavaScript runs:


    <script src="script.js" defer></script>
                        
    • defer: Waits until the HTML is fully loaded, then runs JS (recommended).
    • async: Runs JS as soon as it's loaded (can be unpredictable with DOM access).