2

I want to load some script tag from the server as a string and to append it to HTML header, but even though I can append it, it doesn't execute. Here is the simplified HTML file to illustrate this situation:

<head>

</head>
<body>

    <script>
        function htmlStringToElement(htmlString) {
            var template = document.createElement('template');
            htmlString = htmlString.trim();
            template.innerHTML = htmlString;
            return template.content.firstChild;
        }

        //Mocking http request
        setTimeout(function() {
            var httpResponseMock = '<script>alert("HELLO FROM HTTP RESPONSE!");<\/script>'; 
            var script = htmlStringToElement(httpResponseMock);
            document.head.appendChild(script);
        }, 1000);
    </script>
</body>

I suppose that the reason is that header has already been rendered when the script is added dynamically but is there any other way to achieve this?

1

3 Answers 3

3

With Jquery,

var httpResponseMock = '<script><\/script>'; 
$('head').append(httpResponseMock);

and with javascript

var httpResponseMock = '<script><\/script>'; 
document.getElementsByTagName('head')[0].appendChild(httpResponseMock);
Sign up to request clarification or add additional context in comments.

1 Comment

Well it works if it's done with jQuery as you did in a first example, but the second example without jQuery doesn't work. Anyway jQuery approach is very usefull! Thanks!
3

don't ever use innerHTML unless you know what you are doing.
if you really want to dynamically inject script into the document just do this or use eval:

const script = document.createElement("script");
script.textContent = "console.log('yay it works!');";
document.head.appendChild(script);

the appendChild is running it.

1 Comment

Thanks! This works well. I just added one additional step between because I receive whole script tag as a pure string, but your solution was the key thing to make this work. var httpResponseMock = '<script>alert("HELLO FROM HTTP RESPONSE!");<\/script>'; var parsedScriptFromHttpResponse = htmlStringToElement(httpResponseMock); const script = document.createElement("script"); script.textContent = parsedScriptFromHttpResponse.text; document.head.appendChild(script);
0

There is a longer discussion in another question about dynamic loading of JS. The simple answer in this case is to use eval to evaluate the script content. Please note though that using eval is considered mostly a bad practice.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.