You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何正确移除head标签中的指定script脚本?

正确移除head中指定脚本元素的方法

你当前代码的核心问题是:document.head.removeChild() 要求传入DOM元素对象,但你传的是字符串文件名'temp_values_1.js',所以完全不生效。

下面是两种可行的实现方式:

方法一:用querySelector精准定位

利用脚本的src属性直接匹配目标元素,代码最简洁:

function removeScript() {
  // 通过src属性精准找到目标script元素
  const targetScript = document.querySelector('script[src="http://localhost/static/js/temp_values_1.js"]');
  if (targetScript) {
    // 找到后直接移除元素
    targetScript.remove();
    // 也可以用 document.head.removeChild(targetScript); 效果完全一致
  }
}

方法二:遍历筛选脚本元素

如果担心路径匹配有误差,或者需要批量处理,可以遍历head中的所有脚本:

function removeScript() {
  const scripts = document.head.getElementsByTagName('script');
  // 倒序遍历避免删除元素后索引错乱
  for (let i = scripts.length - 1; i >= 0; i--) {
    const script = scripts[i];
    // 检查src是否包含目标文件名
    if (script.src.includes('temp_values_1.js')) {
      script.remove();
    }
  }
}

重要提醒

移除DOM中的script元素不会撤销已经执行过的脚本代码,只是把这个元素从页面结构中删除,已经运行的逻辑不受影响。

内容的提问来源于stack exchange,提问作者Norman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 12:54:53