脚本预处理的基础知识

Basics of script pre-processing

本文关键字:基础知识 预处理 脚本      更新时间:2023-09-26

我有这个代码:

<script id="toModify" >
Invalid javascript that will cause errors
</script>
<script>
var s=document.getElementById("toModify");
s.innerHTML="alert('Hi')";
</script>

而且它不起作用。

我知道我至少需要做两件事才能使其正常工作:

  • 阻止第一个脚本首次运行。
  • 修改后,重新运行第一个脚本。

我该怎么做这些事情?我还需要做什么吗?

  • 使用 type 属性,以便浏览器不执行脚本:

    <script id="toModify" type="text/x-custom-whatever">...</script>
    
  • 只需eval()代码即可执行它。

当然,动态生成代码充满了危险;要非常小心,不要引入安全漏洞。

为脚本设置与不支持的"text/javascript"不同的类型将使脚本不被处理。

所以<script id="toModify" type="text/unprocessed">...</script>

然后,您可以创建一个类型的新元素 script 设置其 innerHTML 并将其附加到文档中。

类似的东西

var s = document.getElementById("toModify");
var processed = document.createElement('script'); // create a new script element
processed.innerHTML = "alert('Hi')"; // or do something with the s.innerHTML
document.body.insertBefore(processed, document.body.firstChild); // add the new element to the body, it gets executed immediately..

http://jsfiddle.net/GG7cT/演示

你不能。第一个脚本将始终首先运行。即使它具有defer属性,我也不确定您是否能够更改其内容。

另请参阅此答案。