将脚本标记作为字符串加载并将其附加到 html header
Load script tag as a string and append it to html header
我想从服务器加载一些脚本标记作为字符串并将其附加到 HTML header,但即使我可以附加它,它也不会执行。这是说明这种情况的简化 HTML 文件:
<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>
我想原因是动态添加脚本时 header 已经渲染了,但是还有其他方法可以实现吗?
和Jquery,
var httpResponseMock = '<script><\/script>';
$('head').append(httpResponseMock);
和 javascript
var httpResponseMock = '<script><\/script>';
document.getElementsByTagName('head')[0].appendChild(httpResponseMock);
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 中有更长的讨论。
永远不要使用 innerHTML,除非你知道自己在做什么。
如果您真的想将脚本动态注入文档,只需执行此操作或使用 eval:
const script = document.createElement("script");
script.textContent = "console.log('yay it works!');";
document.head.appendChild(script);
appendChild
就是运行了。
我想从服务器加载一些脚本标记作为字符串并将其附加到 HTML header,但即使我可以附加它,它也不会执行。这是说明这种情况的简化 HTML 文件:
<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>
我想原因是动态添加脚本时 header 已经渲染了,但是还有其他方法可以实现吗?
和Jquery,
var httpResponseMock = '<script><\/script>';
$('head').append(httpResponseMock);
和 javascript
var httpResponseMock = '<script><\/script>';
document.getElementsByTagName('head')[0].appendChild(httpResponseMock);
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 中有更长的讨论。
永远不要使用 innerHTML,除非你知道自己在做什么。
如果您真的想将脚本动态注入文档,只需执行此操作或使用 eval:
const script = document.createElement("script");
script.textContent = "console.log('yay it works!');";
document.head.appendChild(script);
appendChild
就是运行了。