使用 Id 删除脚本

Remove a script using Id

我有下面的脚本,我正在嵌入和删除它以嵌入下一个脚本。但是我想通过 id 而不是 head.childNodes[head.childNodes.length - 1] 删除以前的标签。谁能帮忙。

var head = document.getElementsByTagName('head')[0];
    var tag = document.createElement('script');
    tag.type = 'text/javascript';
    tag.id = 'adobedatalayer'
    tag.textContent = "var DDO = {}; DDO.pageData = {'pageName': '" + pageLoadData.pageUrl + "'} ";
    if (this._dataLayerInjected) {
      var script = head.childNodes[head.childNodes.length - 1]; //get previous script element
      head.removeChild(script); //removing script
      head.appendChild(tag); // appending the script again
    } else {
      head.appendChild(tag);
      this._dataLayerInjected = true;
    }

插入时只保留对脚本标记的引用,然后在下次运行这段代码时可以 .remove() 它怎么样?将其放在实例上而不是保存 _dataLayerInjected 标志。您也可以使用 document.head 而不是 document.getElementsByTagName('head')[0];:

// Remove previous script:
if (this.script) {
  this.script.remove();
}
this.script = document.createElement('script');
this.script.id = 'adobedatalayer'; // is this really needed?
this.script.textContent = "var DDO = {}; DDO.pageData = {'pageName': '" + pageLoadData.pageUrl + "'} ";
document.head.appendChild(this.script);
  var head = document.getElementsByTagName('head')[0];
    var tag = document.createElement('script');
    tag.type = 'text/javascript';
    tag.id = 'adobedatalayer';
    tag.textContent = 'var DDO = {}; DDO.pageData =' + JSON.stringify(pageinfo);
    var script = document.getElementById('adobedatalayer');
    if (script != null) {
      head.removeChild(script);
    }
    head.appendChild(tag);