为什么cloneNode <script>标签不执行?

Ale*_*tic 9 javascript dom

克隆的<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

这是我正在研究的一个更大问题的一部分,所以我知道这是一件愚蠢的事情.

aps*_*ers 6

W3C HTML5规范要求此行为.

每个<script>元素都有一个名为" 已启动 " 的属性标志.规范说:

最初,脚本元素必须取消设置此标志(脚本块在创建时不会"已经启动").如果在要克隆的元素上设置了脚本元素的克隆步骤,则必须在副本上设置"已启动"标志.

然后,后来:

如果脚本元素被标记为"已经开始",则用户代理必须在此时中止这些步骤.该脚本未执行.

解决方案不是克隆脚本元素,而是创建使用相同内容填充的全新元素.

  • 是否可以使用 javascript 访问这些标志?对于通过设置innerHTML 添加的脚本,该标志将设置为什么?该脚本位于 DOM 中,但未执行。 (4认同)
  • 我知道已经开始的标志。我假设该标志会在克隆时被清除。可能不会。 (2认同)

Bar*_*mar 5

我不知道为什么它不适用于,但您可以通过将 复制到新的脚本节点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)