Ultimate Guide for Adding JavaScript to Your HTML Pages

Robin
Updated on February 18, 2023

JavaScript is a powerful scripting language that can bring a dynamic and interactive experience to your web pages. That's why as a web developer, you need to know the different ways to add JavaScript to your HTML document.

In this ultimate guide, we'll take you through everything you need to know, from the three main ways to include JavaScript in your HTML pages, to best practices and optimization techniques.

Ready to take your web development skills to the next level?

Let's get started!

How to Add JavaScript to HTML Document

There are three main ways to add JavaScript to an HTML document:

  • Inline Script: Place directly in an HTML element's attribute, typically the onclick or onload attribute.
  • Internal Script: Placed within the <script> tag in the <head> or <body> section of the HTML document.
  • External Script: Write JavaScript code in an external file and link to it from the HTML document using the script tag with the src attribute set to the URL of that external file.

Before discussing each technique in detail, you need to know how browsers parse an HTML document in order to display a web page.

How Browsers Parse an HTML Document

When you load a web page in your browser, the browser goes through a process called parsing to create a structured representation of the page called the Document Object Model (DOM).

Browsers parse the HTML from top to bottom line by line. When it finds JavaScript code, it will start to download and execute them. This means that the page won't start rendering until the browser has downloaded and executed the JavaScript code, which can take some time.

As a result, the user may have to wait longer to see the visible content on the page, which can negatively impact their experience. But don't worry, I will show you how to use these methods in such a way that they don't slow down your web pages.

Also Read: Best Guide on Dynamic Import in JavaScript for Importing Modules

Inline Script: Add JavaScript to HTML Attribute

Inline scripts are JavaScript codes that you add directly to an HTML element using the attribute. For example, you might add an onclick attribute to a button element to trigger JavaScript code when the button is clicked.

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

The JavaScript code in this example is called an inline script because it's included directly in the HTML attribute, rather than in a separate JavaScript file.

While inline scripts are a convenient way to add simple JavaScript functionality to a web page, they can have some drawbacks.

One issue is that it can make your HTML code more difficult to read and maintain, especially if there are a lot of different inline scripts on the page. You can use this when you want to insert a simple and small piece of JavaScript code.

Internal Script: Add JavaScript to HTML Document

An internal script is a block of JavaScript code that we add directly to an HTML document, usually within the <head> or <body> sections of the document. For that, you can use the <script> tag with the code included between the opening and closing tags.

          <html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>How to Add JavaScript to HTML</title>
    <script>
        const myFunc = () => {
            const date = new Date();
            const format = date.toDateString();

            console.log(format)
        }

        myFunc();
    </script>
</head>

<body>
    <!-- ... -->
</body>

</html>
        

In this example, I am using the <script> tag to define a JavaScript function within the <head> element. I am also executing this function here.

When you write the <script> tag within the <head> element, you have to face a problem. That is you can not access any HTML elements using JavaScript code. Because browsers will execute this code before parsing those HTML elements.

          <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>How to Add JavaScript to HTML</title>
</head>

<body>
    <button id="btn">Click Here</button>

    <script>
        const myFunc = () => {
            const date = new Date();
            const format = date.toDateString();

            console.log(format)
        }

        document.getElementById("btn").addEventListener("click", myFunc)
    </script>
</body>

</html>
        

In this example, I have added my JavaScript code at the end of the <body> tag. That's why I am able to access the button element and execute the myFunc() function on button click.

One advantage of using internal scripts is that you can write them within the HTML document itself, which makes the code easier to read and maintain than inline scripts.

But if you use them many times in your HTML document and write complex code, it will become difficult to understand. For long and complex code, it is better to use an external script.

Also Read: How to Preview an Image Using JavaScript Before Upload

External Script: Add JavaScript File to HTML

Most of the time we write our JavaScript code in a separate file with a .js extension and link it to our HTML document using the <script> tag. To include a JavaScript file, you can use the src attribute in the <script> tag with the path of your file.

          <script src="./js/main.js"></script>
        

Suppose, I have a main.js file inside a js folder. When I want to include this file, I will use the above syntax. You have to provide the file path in the src attribute.

You can also link multiple JavaScript files by defining the <script> tag multiple times.

          <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>How to Add JavaScript to HTML</title>
</head>

<body>
    <!-- ... -->

    <script src="./js/functions.js"></script>
    <script src="./js/main.js"></script>
</body>

</html>
        

You can link your external scripts at the bottom of the <body> tag or inside the <head> tag. But the question is which one is the best position?

So far we used to include our external scripts at the end of our <body> tag. Because the browser will parse the document first and then it will download and execute the JavaScript code.

When we add these external scripts in the <head> tag, it will block the document rendering. Therefore, users won't see anything on the screen until browsers finish downloading and executing the JavaScript code.

          <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>How to Add JavaScript to HTML</title>

    <script defer src="./js/functions.js"></script>
    <script defer src="./js/main.js"></script>
</head>

<body>
    <!-- ... -->
</body>

</html>
        

But you can solve this issue by using the async or defer attribute in your <script> tag. With this attribute, you can include your external scripts in the <head> section without any problem.

The async attribute: A browser will download the JavaScript files asynchronously which means it will download the files and parse the HTML document at the same time. But when the download completes, it will stop parsing HTML and start executing JavaScript.

The defer attribute: A browser will also download the JavaScript files and parse the HTML document at the same time. Even if the download completes, it will only execute the code after parsing the HTML document completely.

Also Read: Async VS Defer - When & How to Use Async Defer in HTML Script Tag

These are the benefits of using external scripts in an HTML document:

  • Code separation: Using separate files for JavaScript code, makes it easier to read and maintain.
  • Reusability: External scripts can be reused across multiple pages of your website. You can reduce code duplication with this.
  • Caching: Browsers often cache external JavaScript files which means, a user will download a file once and use it multiple times.
  • Better organization: You can easily manage and organize your JavaScript codes by keeping them in separate files.

Conclusion

We covered several methods of adding JavaScript to your HTML documents in this post. Each method has its own advantages and disadvantages. You can choose any of these methods depending on your specific needs and the complexity of your application.

We also have discussed the best practices for these methods such as when you should use which method and where you should place your JavaScript code in your HTML document.

By following these guidelines, you can add JavaScript to the HTML pages and, improve the performance and maintainability of your code.

Related Posts