如何使用本机JS创建脚本的完整副本?

时间:2016-04-01 12:18:39

标签: javascript

有以下任务 - 我需要创建一个脚本对象的副本(除了src之外的所有属性),即如果有这样的话:

<script src="1" async data-x="bb">

我需要创建一些脚本标记并插入相同的属性,即

<script src="new_src" async data-x="bb">

我试图做以下事情:

var script = document.currentScript;

insert('new_src', script.attributes);

function insert(src, attributes) {
  var script = document.createElement('script');
  script.attributes = attributes;
  script.src = src;

  oldScript.parentNode.insertBefore(script, oldScript.nextSibling);
}

插入了新脚本,但除了src之外还有空属性。我该怎么办?提前致谢!仅使用原生JS

1 个答案:

答案 0 :(得分:1)

通过cloneNode

可以实现将attributes从一个元素存储到另一个元素的方法
var newScript = document.currentScript.cloneNode();
// newScript has the same attributes as, document.currentScript
// now you can overwrite the src attribute,
newScript.src = "new_src";

这样,您的insert功能可以重写为

function insert(src, node) {
  var script = node.cloneNode();
  script.src = src;
  node.parentNode.insertBefore(script, node.nextSibling);
}

我在下面的开发人员工具中测试过,

# grabbed the first <script> tag on the page for brevity,
> insert("whatever",$$("script")[0])

# lets view the <script> tag we cloned from,
> $$("script")[0]
# returns, <script type=​"text/​javascript" async src=​"http:​/​/​engine.adzerk.net/​ados?t=1459514526146&request=...,"IsAsync":​true}​">​</script>​

# check the attributes on the cloned element,
> $$("script")[0].nextSibling
# returns, <script type=​"text/​javascript" async src=​"whatever">​</script>​