Insert Scripts Using innerHTML in JavaScript

You can use JavaScript and work with the DOM by adding HTML content to the webpage. You can use the innerHTML property for this purpose because it allows you to change the structure and content of elements. In this blog, we will discuss how to add scripts using innerHTML, its limitations, and other ways to add and execute JavaScript on your webpage.

 

Table of Contents:

Understanding innerHTML and Its Limitations

You can use the innerHTML property to get or set the HTML content inside the element.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>innerHTML Example</title>
</head>

<body>
    <div id="content"></div>
    <script>
        let div = document.getElementById("content");
        div.innerHTML = "<h2>Intellipaat!</h2>";
    </script>
</body>
</html>

Output:

Understanding innerHTML and Its Limitations

This can work well with the HTML element, but it has some limitations for JavaScript.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>innerHTML Script Issue</title>
</head>

<body>
    <div id="content"></div>
    <script>
        let div = document.getElementById("content");
        div.innerHTML = "<script>alert('This will not execute');</script>";
    </script>
</body>
</html>

Even if the <script> tag is present inside the DOM, the browser won’t run it. This is to prevent cross-site attacks, it is one of the security features.

Design. Build. Launch Your Dream Career
Become a Web Developer – Enroll Now!
quiz-icon

Method to Insert and Execute Scripts

You can use createElement and appendChild, setting the src Attribute, insertAdjacentHTML, Function Constructor, DOMContentLoaded Event, Fetch API, script.onload for Callback Execution, and jQuery to inject and Execute Scripts. Let us discuss these methods below.

Method 1: Using createElement and appendChild

In this method, the new script can be created, and the script is added to the DOM. The browser can detect this process and run it after the element is added to the DOM.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>Using createElement</title>
</head>

<body>
    <script>
        let script = document.createElement("script");
        script.textContent = "alert('Script executed!');";
        document.body.appendChild(script);
    </script>
</body>
</html>

Output:

Using createElement and appendChild

Explanation: The <script> element is created by the document.createElement. The script is added to the document.body.appendChild, followed by getting the alert message.  

Method 2: Setting the src Attribute

The external script can be added using the src attribute. Followed by validation of the JavaScript URL and adding it to the document.  

Example:

<!DOCTYPE html>
<html>
<head>
    <title>Loading jQuery</title>
</head>

<body>
    <script>
        let script = document.createElement("script");
        script.src = "https://code.jquery.com/jquery-3.6.0.min.js";
        script.async = true;
        script.onload = function() {
            if (typeof jQuery !== 'undefined') {
                alert("jQuery has been loaded and is ready to use!");
            } else {
                alert("jQuery failed to load.");
            }
        };
        document.body.appendChild(script);
    </script>
</body>
</html>

Output:

Setting the src Attribute

Explanation: In the example, code loads jQuery by creating a <script> element and setting its src attribute. After that, an alert message confirms successful execution of the code.

Method 3: Using insertAdjacentHTML

This method helps you add raw HTML into the DOM at a particular place. But the problem here was that the browser could not run it. If the file includes this way, you should apply some proper validation to avoid this problem.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>Using insertAdjacentHTML Alternative</title>
</head>

<body>
    <script>
        document.body.insertAdjacentHTML("beforeend", "<div>Script is being added dynamically...</div>");
        let script = document.createElement("script");
        script.textContent = "alert('Inserted script executed!');"; // Script content
        document.body.appendChild(script); // Append to execute it
    </script>
</body>
</html>

Output:

Using insertAdjacentHTML

Explanation: You can use this code to add a <div> with a message using insertAdjacentHTML and create a <script> element with an alert message.

Method 4: Using Function Constructor

You can use the Function constructor to run JavaScript. This method is considered to be safer than eval() because it creates its own function scope.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>Function Constructor</title>
</head>

<body>
    <script>
        let executeScript = new Function("alert('Executed using Function constructor!');");
        executeScript();
    </script>
</body>
</html>

Output:

Using Function Constructor

Explanation: In the example, you create a function constructor, and executeScript() is used for calling the function. And you will get the alert message upon execution.     

Method 5: Using DOMContentLoaded Event

You can use this method to run the scripts only after the DOM has completely loaded, making it helpful for adding scripts at the right time.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>DOMContentLoaded Example</title>
</head>

<body>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            let script = document.createElement("script");
            script.textContent = "alert('Executed after DOM loaded!');";
            document.body.appendChild(script);
        });
    </script>
</body>
</html>

Output:

Using DOMContentLoaded Event

Explanation: You can use this code to run the script when the DOM is fully loaded. You can use the DOMContentLoaded event listener to wait for the DOM to get ready. Then, you can create the script and get notified with an altered message for execution.  

Method 6: Using Fetch API

Fetch API can be usedto add the external script. You can get the script, turn it into text, and run it after adding it to the DOM. 

Example:

<!DOCTYPE html>
<html>
<head>
    <title>Fetch API Script Injection (Alternative)</title>
</head>

<body>
    <script>
        async function loadAndExecuteScript(url) {
            try {
                let res = await fetch(url);
                if (!res.ok) {
                    throw new Error(`Failed to load script: ${res.statusText}`);
                }
                let scriptContent = await res.text();
                let script = document.createElement("script");
                script.textContent = scriptContent;
                document.body.appendChild(script);
                alert("Script loaded and executed successfully!");

            } catch (error) {
                console.error(error);
                alert("Error loading script!");
            }
        }
        loadAndExecuteScript("https://code.jquery.com/jquery-3.6.0.min.js");
    </script>
</body>
</html>

Output:

Using Fetch API

Explanation: This code makes the script get added externally using the Fetch API. This method loads the content into the <script> tag and then is sent for execution in the DOM.

Method 7: Using script.onload for Callback Execution

In this method, you can run the script only after the script has been loaded. You can also use this method to manage its dependencies.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>Script onload Example</title>
</head>

<body>
    <script>
        let script = document.createElement("script");
        script.src = "https://code.jquery.com/jquery-3.6.0.min.js";
        script.onload = function() {
            alert("External script has been loaded and executed!");
        };

        script.onerror = function() {
            alert("Failed to load the script!");
        };
        document.body.appendChild(script);
    </script>
</body>
</html>

Output:

Using script.onload for Callback Execution

Explanation: In this example, the script is set to the src attribute. And the onload function is used to trigger the alert message.      

Get 100% Hike!

Master Most in Demand Skills Now!

Method 8: Using jQuery to Inject and Execute Scripts

You can use this method to add the script externally using the $.getScript() function in jQuery.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery Script Injection</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<body>
    <script>
        $.getScript("https://code.jquery.com/jquery-3.6.0.min.js")
            .done(function() {
                alert("External script has been loaded successfully!");
            })
            .fail(function() {
                alert("Failed to load the script!");
            });
    </script>
</body>
</html>

Output:

Using jQuery to Inject and Execute Scripts

Explanation: In this example, the script gets added externally using the jQuery $.getScript() function. And done() function is used to trigger the alert message.     

Conclusion

The innerHTML is used to load the HTML elements, but when it comes to the scripts, you can see that it has some limitations. You can use createElement with appendChild, setting the src attribute, insertAdjacentHTML, the Function constructor, DOMContentLoaded event, Fetch API, script.onload for callbacks, or jQuery’s $.getScript() methods for this purpose. All of these methods ensure that the process is safe for adding scripts. 

Insert Scripts Using innerHTML in JavaScript – FAQs

Q1. Can you insert scripts into the DOM using innerHTML?

Yes, you can use innerHTML to insert <script> tags into the DOM.

Q2. Why doesn’t the browser execute scripts added with innerHTML?

The browser doesn’t execute scripts added with innerHTML because it poses a risk of cross-site scripting (XSS) attacks.

Q3. What are the alternative ways to execute scripts?

You can use methods like createElement with appendChild, Function constructor, or jQuery to execute scripts.

Q4. Is innerHTML safe for adding HTML?

Yes, innerHTML is safe for HTML elements, but inserting a script without proper validation can create a problem in your code.

Q5. What is a better way to load and execute external scripts?

You can use the createElement to add a <script> tag and put the src attribute.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner