如何使用原生JS创建脚本的完整副本

How to create full copy of a script using native JS?

本文关键字:副本 脚本 创建 何使用 原生 JS      更新时间:2023-11-07

有以下任务-我需要创建脚本对象的副本(除了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

通过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>​