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

如何通过if/else语句根据URL调用不同的JS脚本

你的代码不可行

你贴的这段代码没法正常运行,原因很简单:在JavaScript代码块里直接写<script>标签属于语法错误,JS引擎根本识别不了这种HTML语法。

要实现根据URL路径加载不同脚本的需求,得用JavaScript的DOM API动态创建脚本元素,下面是可行的写法:

写法一(三元表达式简化版)

const script = document.createElement('script');
script.type = 'text/javascript';
script.src = window.location.pathname === '/search' ? 'file1.js' : 'file2.js';
document.head.appendChild(script);

写法二(if/else清晰版)

let targetScript;
if (window.location.pathname === '/search') {
  targetScript = 'file1.js';
} else {
  targetScript = 'file2.js';
}

const script = document.createElement('script');
script.type = 'text/javascript';
script.src = targetScript;
document.head.appendChild(script);

把这段代码放到<head>标签里,就能根据当前URL的路径,自动加载对应的脚本文件,满足你基于URL构建DOM的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 17:01:07