Log In

How to Add JavaScript to HTML

How to Add JavaScript to HTML
23.11.2023
Reading time: 6 min
Hostman Team
Technical writer

In this article, let's understand how to add JavaScript to HTML. There are three ways to do it:

  • Place JS code inside a paired <script> tag;

  • Connect an external file;

  • Write the code directly inside the HTML tag using special attributes. 

Let's take a look at each method to understand its pros and cons.

Inserting code inside a paired <script> tag

The easiest way to insert JS code into an HTML page is to use the <script> paired tag. It tells the browser to interpret all its content as an executable script, not as text or HTML code. 

For example, let's add a script to the page displaying the current date and time.

<!DOCTYPE html>
<html lang="en">
 <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Date and Time</title>
</head>
<body>
    <script>
        let date = new Date();
        alert("Now " + date);
    </script> 
</body>  
</html>

When the page loads, a notification with the current date and time will appear.

You can write a whole program inside the <script> tag. As an example, let's create an electronic clock.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Electronic Clock</title>
<script>
function displayTime() {
    let element = document.getElementById("clock"); // Find element with id="clock" 
    let now = new Date(); // Get current time
    element.innerHTML = now.toLocaleTimeString(); // Display time
    setTimeout(displayTime, 1000); // Call the function every second
}
window.onload = displayTime; // Start displaying the time after the document is loaded
</script>
</head>
<body>
    <h1>Electronic Clock</h1>. 
    <div id="clock"></div>
</body>
</html>

Great! You have used JavaScript to add information about the current time, which is updated every second, to the HTML element.

The comments describe in detail what the script does. It finds the element with id='clock' located in the <div> tag inside the body section just below the header. The program then gets the current time, displayed immediately after the document is loaded and updated every second.

It looks convenient, but this approach has a few disadvantages. Imagine that you want to display the time on every site page. In this case, you will have to duplicate the content of the <script> tag. 

Another problem is that the larger the script content, the worse the readability of the code. In the example above, there is only one function. But if you need 5, 10, or 20 of them to implement the required behavior, it is more convenient to use the following approach - to connect JS code from external files.

Connecting external files

The <script> tag is also used to connect JavaScript from external files by adding a src attribute, in which you specify a link to the JS file. It can be a file created by you and stored next to HTML or in another directory. It can also be a JS library file that adds the desired behavior to the page.

For example, let's take a script that displays the current time. Let's transfer all the logic to a separate file:

# Time.js file
function displayTime() {
    let element = document.getElementById("clock"); // Find element with id="clock" 
    let now = new Date(); // Get current time
    element.innerHTML = now.toLocaleTimeString(); // Display time
    setTimeout(displayTime, 1000); // Call the function every second
}
window.onload = displayTime; // Start displaying the time after the document is loaded

You can remove all JS code from the HTML file. Only the <script> tag, which contains a link to the time.js file via the src attribute, will remain:

#File time.html
<html>
<head>
    <meta charset="utf-8">
    <title>Electronic Clock</title>
    <script src="./time.js"></script>
</head>
<body>
    <h1>Electronic Clock</h1> 
    <div id="clock"></div>
</body>
</html>

The result will be the same - you've added the current time information to the HTML div using JavaScript.

This approach has several advantages at once:

  1. HTML files become simpler. They only contain content and links to external files.

  2. You can keep all JS code in one file and plug it into different pages as needed.

  3. If multiple pages use a single script, it will be fully loaded only once and then reused from the browser cache.

JS inside HTML tags

You can place JavaScript inside an HTML tag using special attributes: onclick, onmouseover, onkeypress, onload, etc. These add event handlers to elements. 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>JavaScript inside an HTML tag</title>        
</head>
<body>    
    <button onclick="alert('Hi! This is how JS works too')">Click me</button>
    <button onmouseover="alert('This works too')">Hover over me</button>
</body>
</html>

If you click the first button, you will see a browser notification with the text "Hi! JS works like this too". If you hover your mouse over the second button, a browser notification with the text "This works too" will appear in response. It indicates that the event handler works correctly and responds to user actions. 

You can add multiple attributes with event handlers to a single tag by separating them with semicolons. It goes like this:

<button onclick="alert('Hi! This is how JS works too')" ; onmouseover="alert('This works too')">Click me</button>

However, this is a bad practice. Most developers prefer to separate content and behavior control into different files. Besides, as you can see, using handlers inside HTML significantly degrades code readability.

Where best to place scripts

Technically, there are no restrictions on inserting the <script> tag. You can add JavaScript on the page in the <head> and <body> sections at the beginning and end of the document. All of these options will work.

However, scripts are usually placed at the end of the body section, right before the closing tag. It makes the page load quicker. Users see the content faster and realize that the page is working. Even if JS loads a little later, it doesn't degrade the user experience as much as waiting a long time for the page to render.

The point is that each <script> tag blocks page rendering until JS is fully loaded and executed. But connected files (and sometimes entire libraries) can weigh quite a lot. At high internet speed, the pause can be minimal. But if the user is in a place with poor cellular coverage, he will notice that the site does not display content for a very long time.

You should place scripts in the head section only if you have a reason to. For example, without JS, no content is displayed on the page at all. But if there are no such reasons, and you are worried about the page loading speed, it is better to add JavaScript to the HTML code at the end of the document before the closing </body> tag.


Share