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?
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?
Share Improve this question edited Dec 6, 2018 at 8:50 Maksym Labutin 5711 gold badge8 silver badges17 bronze badges asked Dec 6, 2018 at 8:16 Mladen KrstićMladen Krstić 1983 silver badges12 bronze badges 1- Does this answer your question? How do I include a JavaScript file in another JavaScript file? – ggorlen Commented Aug 6, 2020 at 5:43
3 Answers
Reset to default 3With Jquery,
var httpResponseMock = '<script><\/script>';
$('head').append(httpResponseMock);
and with javascript
var httpResponseMock = '<script><\/script>';
document.getElementsByTagName('head')[0].appendChild(httpResponseMock);
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.
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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744754966a4591825.html
评论列表(0条)