脚本预处理的基础知识

时间:2012-07-02 18:40:48

标签: javascript preprocessor

我有这段代码:

<script id="toModify" >
Invalid javascript that will cause errors
</script>

<script>
var s=document.getElementById("toModify");
s.innerHTML="alert('Hi')";
</script>

它不起作用。

我知道至少有两件事我需要做才能起作用:

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

我该怎么办?还有什么我需要做的吗?

3 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:1)

将类型设置为与“text / javascript”不同的脚本将使脚本无法处理。

所以<script id="toModify" type="text/unprocessed">...</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/

演示

答案 2 :(得分:-1)

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

另见this answer

相关问题