克隆的<script>标记不会执行.为什么?
例:
<script id="hello">
console.log("hello execution count ", window.helloCount++);
</script>
<script id="action">
document.body.appendChild(
document.getElementById('hello').cloneNode(true));
console.log('cloned the script');
</script>
Run Code Online (Sandbox Code Playgroud)
执行后,文档中有两个hello脚本,但只执行了一个.
http://jsbin.com/zuxoro/1/edit?html,console,output
这是我正在研究的一个更大问题的一部分,所以我知道这是一件愚蠢的事情.
W3C HTML5规范要求此行为.
每个<script>元素都有一个名为" 已启动 " 的属性标志.规范说:
最初,脚本元素必须取消设置此标志(脚本块在创建时不会"已经启动").如果在要克隆的元素上设置了脚本元素的克隆步骤,则必须在副本上设置"已启动"标志.
然后,后来:
如果脚本元素被标记为"已经开始",则用户代理必须在此时中止这些步骤.该脚本未执行.
解决方案不是克隆脚本元素,而是创建使用相同内容填充的全新元素.
我不知道为什么它不适用于,但您可以通过将 复制到新的脚本节点cloneNode来获得相同的结果。innerHTML
var clone = document.createElement('script');
clone.innerHTML = document.getElementById('hello').innerHTML;
document.body.appendChild(clone);
console.log('copied the script');Run Code Online (Sandbox Code Playgroud)
<script>
window.helloCount = 1;
</script>
<script id="hello">
console.log("hello execution count ", window.helloCount++);
</script>
<div>Copied scripts do execute</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1215 次 |
| 最近记录: |