简体   繁体   English

将脚本标签加载为字符串并将其附加到html标头

[英]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. 我想从服务器以字符串形式加载一些脚本标记并将其附加到HTML标头中,但是即使我可以附加它,它也不会执行。 Here is the simplified HTML file to illustrate this situation: 这是简化的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>

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? 我想这是因为在动态添加脚本时已经渲染了标头,但是还有其他方法可以实现吗?

With Jquery, 使用Jquery,

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

and with javascript 并使用javascript

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

don't ever use innerHTML unless you know what you are doing. 除非您知道自己在做什么,否则永远不要使用innerHTML。
if you really want to dynamically inject script into the document just do this or use eval: 如果您真的想将脚本动态注入文档中,请执行以下操作或使用eval:

 const script = document.createElement("script"); script.textContent = "console.log('yay it works!');"; document.head.appendChild(script); 

the appendChild is running it. appendChild正在运行它。

There is a longer discussion in another question about dynamic loading of JS. 关于JS动态加载的另一个问题还有更长的讨论。 The simple answer in this case is to use eval to evaluate the script content. 在这种情况下,简单的答案是使用eval评估脚本内容。 Please note though that using eval is considered mostly a bad practice . 请注意,尽管使用eval通常被认为是一种不好的做法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM