Skip to content

Where is the correct place to insert JavaScript?

  • by

The correct place to insert JavaScript code in an HTML document can depend on the specific use case, but generally, there are three common places to insert JavaScript code:

  1. Inline: You can insert JavaScript code inline within HTML tags.
  2. External file: If you have a lot of JavaScript code, placing it in an external file and linking to it from your HTML document using the tag is often better. This makes it easier to manage and reuse your code.
  3. At the end of the document: Another common approach is to place JavaScript code at the end of your HTML document, just before the closing </body> tag. This ensures that the HTML content is loaded before the JavaScript code runs.

Ultimately, the best place to insert JavaScript code depends on your specific use case and the structure of your HTML document.

Read this tutorial for examples: Where to put JavaScript in an HTML Document

Example the correct place to insert JavaScript

Simple example code.

<!DOCTYPE html>
<html>
  <head>
    <title>My HTML Page</title>
  </head>
  <body>
    <h1>Welcome to my page!</h1>
    
    <form>
      <label for="name">Enter your name:</label>
      <input type="text" id="name" name="name">
      <button type="submit">Submit</button>
    </form>
    
    <script>
      // JavaScript code to handle form submission
      const form = document.querySelector('form');
      form.addEventListener('submit', (event) => {
        event.preventDefault();
        const name = document.querySelector('#name').value;
        alert(`Hello, ${name}!`);
      });
    </script>
  </body>
</html>

Output:

Where is the correct place to insert JavaScript?

Inline

<button onclick="alert('Hello World!')">Click Me!</button>

External file

<script src="path/to/my-script.js"></script>

At the end of the document

<body>
  <!-- HTML content goes here -->
  
  <script>
    // JavaScript code goes here
  </script>
</body>

Comment if you have any doubts or suggestions on this JS basic code.

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading