Three Methods to Add JavaScript to a Website

There are three methods to add JavaScript to a website. These methods include Inline JavaScript, Internal JavaScript and External JavaScript.

There are three methods to add JavaScript to a website. These methods include Inline JavaScript, Internal JavaScript and External JavaScript.

First Method – Inline JavaScript

In this method you can insert JavaScript without using HTML script element and also without creating a separate JavaScript file. Inline JavaScript can be also used in combination with HTML script element and external JS. It is a clever method to insert a quick fix to a website. However adding inline JavaScript is considered a bad SEO practice by the developer community. HTML Page Loading Speed is reduced if JavaScript is added inside HTML page.

Event handlers(Not same as event listeners) can be triggered using inline JS.

  <body>
    <button class="button-style">
      <a
        class="button-style"
        href="#"
        onclick="alert('Hello Teczpert, You are using Inline Javascript')"
        >Teczpert Click Me
      </a>
    </button>
  </body>

TECZPERT DATE AND TIME

Call a function from external JS using inline JavaScript. In this function current date and time is called.

HTML Code

  <body>
    <h1>Teczpert Time Display Clock</h1>
    <h3>Click on the button below to show Date and Time</h3>
    <button onclick="showDateAndTime()">Date and Time</button>
    <p class="time"></p>
    <script src="script.js" charset="UTF-8"></script>
  </body>
</html>

External JS File Code

"use strict";

function showDateAndTime() {
  document.querySelector(".time").innerHTML = Date();
}

Second Method – Internal JavaScript

Script element is used inside HTML file and external JS file is not required.

  <body>
    <h1>Teczpert Key Press Event</h1>
    <h3>
      Click on any key in the keyboard inside input form to display an Alert
      Message
    </h3>
    <input id="keyPress" />
    <script>
      function pressKey() {
        document
          .getElementById("keyPress")
          .addEventListener("keypress", keyClick);
      }

      function keyClick() {
        alert(`Warning... Evacuate Immediately⚠️⚠️⚠️`);
      }

      pressKey();
    </script>
  </body>

Third Method – External JavaScript

This is the most common method used by developers to add JavaScript files. This is the most SEO friendly approach to add JS to a website.

Create a file named anyname.js inside your work folder and then add the anyname.js inside html using script src method.

  <body>
  
    <h1>Hello Teczpert</h1>

    <script src="anyname.js" charset="UTF-8"> </script>
    
  </body>

Always link external script after all code inside HTML body element is written to ensure that JS is loaded after HTML is loaded.