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

如何使用JavaScript正确创建多个script标签?

代码修改方案

你的代码存在两个问题:

  • 函数仅处理单个URL,传入数组时会被自动转换为逗号分隔的字符串,导致生成单个标签
  • script标签加载外部脚本需要使用src属性,而非href(href是link标签的专属属性)

以下是两种可行的修改方案:

方案一:让函数支持数组输入

修改函数逻辑,使其兼容单个URL和URL数组两种输入:

function impScript(scriptURLs) {
  const head = document.querySelector('head');
  // 统一转为数组处理,兼顾单个URL的调用场景
  const urls = Array.isArray(scriptURLs) ? scriptURLs : [scriptURLs];
  // 遍历每个URL,创建独立的script标签
  urls.forEach(url => {
    const script = document.createElement('script');
    script.setAttribute('src', url);
    head.appendChild(script);
  });
}

const metaScript = ['ar.js','ar2.js'];
impScript(metaScript);

方案二:调用时遍历数组

如果不想改动原函数逻辑,在调用阶段循环数组逐个传入URL即可:

function impScript(scriptURL) {
  const head = document.querySelector('head');
  const script = document.createElement('script');
  script.setAttribute('src', scriptURL); // 修正为src属性
  head.appendChild(script);
}

const metaScript = ['ar.js','ar2.js'];
// 遍历数组,逐个调用函数生成标签
metaScript.forEach(url => impScript(url));

两种方案都能生成你需要的独立script标签,同时修正了属性错误,确保外部脚本可以正常加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 14:50:11