【问题标题】:Load script tag as a string and append it to html header将脚本标记作为字符串加载并将其附加到 html 标头
【发布时间】:2018-12-06 16:50:25
【问题描述】:

我想从服务器加载一些脚本标记作为字符串并将其附加到 HTML 标头,但即使我可以附加它,它也不会执行。以下是用于说明这种情况的简化 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>

我想原因是动态添加脚本时已经渲染了标题但是还有其他方法可以实现吗?

【问题讨论】:

标签: javascript html script-tag


【解决方案1】:

使用 Jquery,

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

使用 javascript

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

【讨论】:

  • 好吧,如果它像在第一个示例中那样使用 jQuery 完成,那么它可以工作,但是没有 jQuery 的第二个示例不起作用。无论如何,jQuery 方法非常有用!谢谢!
【解决方案2】:

除非您知道自己在做什么,否则永远不要使用 innerHTML。
如果您真的想将脚本动态注入到文档中,只需执行此操作或使用 eval:

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

appendChild 正在运行它。

【讨论】:

  • 谢谢!这很好用。我只是在两者之间添加了一个额外的步骤,因为我将整个脚本标记作为纯字符串接收,但是您的解决方案是使这项工作发挥作用的关键。 var httpResponseMock = '
【解决方案3】:

another question 中有一个关于动态加载 JS 的较长讨论。在这种情况下,简单的答案是使用eval 来评估脚本内容。请注意,虽然使用eval 主要被认为是bad practice

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-24
    • 2021-07-06
    • 1970-01-01
    • 2014-01-11
    • 2015-12-16
    • 1970-01-01
    • 2018-06-07
    • 2013-05-27
    相关资源
    最近更新 更多