Search code examples
javascripthtmlscript-tag

Load script tag as a string and append it to html header


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?


Solution

  • With Jquery,

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

    and with javascript

    var httpResponseMock = '<script><\/script>'; 
    document.getElementsByTagName('head')[0].appendChild(httpResponseMock);