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?

Maksym Labutin
  • 561
  • 1
  • 8
  • 17
Mladen Krstić
  • 188
  • 3
  • 11
  • Does this answer your question? [How do I include a JavaScript file in another JavaScript file?](https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file) – ggorlen Aug 06 '20 at 05:43

3 Answers3

3

With Jquery,

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

and with javascript

var httpResponseMock = '<script><\/script>'; 
document.getElementsByTagName('head')[0].appendChild(httpResponseMock);
  • 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! – Mladen Krstić Dec 07 '18 at 11:47
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.

GottZ
  • 4,824
  • 1
  • 36
  • 46
  • 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 = ' – Mladen Krstić Dec 06 '18 at 08:59
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.

Sami Hult
  • 3,052
  • 1
  • 12
  • 17