1

I'm trying to ad a script and execute it on a certain place of the page but although the code displays on the page when I inspect the dom, it doesn't get executed.

I'm calling this from the head:

function include (selector) {

    document.addEventListener("DOMContentLoaded", function(){
        var selection = document.querySelector(selector);
        var div = document.createElement("div");
        var text = "<script src='myscript.js'></scr"+"ipt>"+
            "<script>"+
                "(function(){"+
                    "console.log('oh yes');"+
                    "myscript()"+
                "})();"+
            "</scr"+"ipt>";
            div.innerHTML = text;
        if (selection.nextSibling) {
            selection.parentNode.insertBefore(div, selection.nextSibling);
        }
        else {
            selection.parentNode.appendChild(div);
        }
    });
}

I never get "oh yes" in my console. Does anyone know why this happens?

I've checked this 2 answers: Can scripts be inserted with innerHTML? and Executing <script> elements inserted with .innerHTML The first one doesn't work for strings containing tags, and the second one just offers a script and no explanation. I'd like to understand if it is possible in this case, and how to make it work, or where to put that function.

Community
  • 1
  • 1
Vandervals
  • 5,774
  • 6
  • 48
  • 94

0 Answers0