Reputation: 198
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?
Upvotes: 2
Views: 4264
Reputation: 4947
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.
Upvotes: 3
Reputation: 3082
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.
Upvotes: 0
Reputation:
With Jquery,
var httpResponseMock = '<script><\/script>';
$('head').append(httpResponseMock);
and with javascript
var httpResponseMock = '<script><\/script>';
document.getElementsByTagName('head')[0].appendChild(httpResponseMock);
Upvotes: 3