为什么不克隆Node< script>标签执行? [英] Why don't cloneNode <script> tags execute?

查看:105
本文介绍了为什么不克隆Node< script>标签执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

克隆的< 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('克隆脚本');
< / script>

执行后,文档中有两个hello脚本,但只有一个已执行。 >

http://jsbin.com / zuxoro / 1 / edit?html,控制台,输出



这是我正在处理的更大的问题的一部分,所以我知道这是一个愚蠢的

解决方案

此行为是 W3C HTML5规范



每个< script> 元素具有名为已经开始的属性标志。规范说:


最初,脚本元素必须将此标志设置为未设置(脚本块,创建时不是已经启动)。 脚本元素的克隆步骤必须在复制的元素上设置已经开始的标志。


然后,稍后:


如果脚本元素被标记为已经开始,那么用户此时代理人必须中止这些步骤。脚本不执行。


该解决方案根本不是克隆脚本元素,而是创建全新的元素,相同的内容。


Cloned <script> tags do not execute. Why?

Example:

<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>

After execution, there are two hello scripts in the document, but only one has executed.

http://jsbin.com/zuxoro/1/edit?html,console,output

This is part of a larger problem I am working on, so I know it is a dumb thing to do.

解决方案

This behavior is required by the W3C HTML5 specification.

Each <script> element has a property flag called "already started". The specification says:

Initially, script elements must have this flag unset (script blocks, when created, are not "already started"). The cloning steps for script elements must set the "already started" flag on the copy if it is set on the element being cloned.

And then, later:

If the script element is marked as having "already started", then the user agent must abort these steps at this point. The script is not executed.

The solution is simply not to clone script elements, but to create completely new elements that are populated with the same content.

这篇关于为什么不克隆Node&lt; script&gt;标签执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆