Open In App

Prevention from getting error by adding script tag anywhere using DOMContentLoaded Event Listener of JavaScript

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how can we prevent getting the error on the console by adding the script tag anywhere inside the body tag of HTML.

On adding the script at the top we will be getting the error in a different form such that piece of code will not work on the page but the error will be displayed on the console of the developer menu.

The below code will throw an error as the document is not loaded on the console tab.

  

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta name="viewport"
          content="width=device-width,
                   initial-scale=1.0">
    <title>
        Prevention from getting error by adding script tag
    </title>
    <style>
        .common {
            width: 200px;
            height: 60px;
            margin: 20px;
            background-color: rgba(0, 0, 255, 1);
            border-radius: 15px;
            font-size: large;
            color: white;
        }
    </style>
</head>
 
<body>
    <button id="btn1" class="common">
        Button1
    </button>
 
    <script>
        const btn1 = document.getElementById("btn1");
        const btn2 = document.getElementById("btn2");
        btn1.addEventListener("click", function (e) {
            alert("Btn1 is pressed");
        });
        btn2.addEventListener("click", function (e) {
            alert("Btn2 is pressed");
        });
    </script>
 
    <button id="btn2" class="common">
        Button2
    </button>
</body>
 
</html>


Output:

 

The reason for getting the above Error is that (as we can see in the above code) the button having id “btn2”  has been created after adding the script tag due to which the button document has been loaded by the getElementById() method. In order to resolve this error, we can use the DOMContentLoaded Event Listener.

DOMContentLoaded Event Listener: In JavaScript, there is an event Listener that will prevent getting an error on the console named “DOMContentLoaded” on adding the script tag anywhere in the HTML. Because initially, it loads the HTML Document and then the <script> tag due to which all documents are found and loaded easily in the script tag by different methods of js.

Syntax:

document.addEventListener("DOMContentLoaded", function(){
    // javascript code here
})

This event listener’s work is to load the HTML code first and then load the <script> tag because this script tag can be added anywhere in the HTML it doesn’t matter and the code will work fine without any error. We will be seeing the implementation by adding the script tag at two different places inside the HTML code that are:

  • Adding the script tag at the top
  • Adding the script tag in the middle

 Example 1: Adding the script tag at the top

In this example, we will be adding the script tag at the top of the body tag.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta name="viewport"
          content="width=device-width,
                   initial-scale=1.0" />
    <title>
        Prevention from getting error by adding script tag
    </title>
    <style>
        h1 {
            color: darkblue;
        }
 
        .common {
            width: 200px;
            height: 60px;
            margin: 20px;
            background-color: rgba(0, 0, 255, 1);
            border-radius: 15px;
            font-size: large;
            color: white;
        }
 
        #btn1:hover {
            background-color: royalblue;
        }
 
        #btn2:hover {
            background-color: royalblue;
        }
 
        .createdDynamic {
            display: block;
            color: green;
            font-size: 30px;
            width: 200px;
            height: auto;
            margin-left: 20px;
            background-color: lightgray;
            text-align: center;
        }
    </style>
</head>
 
<body>
    <script>
        document.addEventListener("DOMContentLoaded", function (e) {
            const button = document.getElementById("btn1");
            const container = document.getElementById("container");
            button.addEventListener("click", function (e) {
                alert("Message will be displayed")
                const createSpan = document.createElement("span");
                createSpan.className = "createdDynamic";
                createSpan.textContent =
                    "GeeksforGeeks";
                container.appendChild(createSpan);
            });
        });
    </script>
 
    <h1>
        Script tag at the TOP
    </h1>
    <button id="btn1"
            class="common">
            Message
    </button>
    <div id="container"></div>
</body>
 
</html>


Output:

 

Example 2: Adding the script tag in the Middle

In this example, we will add the script tag in the middle of the body tag.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>
        Prevention from getting error by adding script tag
    </title>
    <style>
        h1 {
            color: darkblue;
        }
 
        .common {
            width: 200px;
            height: 60px;
            margin: 20px;
            background-color: rgba(0, 0, 255, 1);
            border-radius: 15px;
            font-size: large;
            color: white;
        }
 
        #btn1:hover {
            background-color: royalblue;
        }
 
        #btn2:hover {
            background-color: royalblue;
        }
 
        .createdDynamic {
            display: block;
            color: green;
            font-size: 30px;
            width: 200px;
            height: auto;
            margin-left: 20px;
            background-color: lightgray;
            text-align: center;
        }
    </style>
</head>
 
<body>
    <h1>
        Script Tag in the Middle
    </h1>
    <button id="btn1"
            class="common">
            Message
    </button>
    <div id="container"></div>
 
    <script>
        document.addEventListener("DOMContentLoaded", function (e) {
            const button = document.getElementById("btn1");
            const container = document.getElementById("container");
            button.addEventListener("click", function (e) {
                alert("Message will be displayed")
                const createSpan = document.createElement("span");
                createSpan.className = "createdDynamic";
                createSpan.textContent =
                    "GeeksforGeeks";
                container.appendChild(createSpan);
            });
            const button2 = document.getElementById("btn2");
            button2.addEventListener('click', function (e) {
                alert("Message removing alert");
                const store = document.getElementById("container");
                if (store.textContent != "") {
                    store.textContent = "";
                }
            });
        });
    </script>
    <button id="btn2"
            class="common">
            Remove Message
    </button>
</body>
 
</html>


Output:

 

Conclusion: As you can see in the above examples it doesn’t matter that where we are creating a document in the HTML code either above the script tag or below the <script> tag and easily loaded all the documents of HTML code because of DOMContentLoaded Event Listener. 



Last Updated : 28 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads