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

点击链接按需加载JS文件的技术实现方案咨询

动态按需加载JS文件实现方案

核心思路

通过点击链接时动态创建script标签加载对应JS文件,替代提前批量引入的方式,实现页面初始快速加载;同时利用data-*属性给链接绑定对应脚本路径,统一处理点击逻辑,避免为上百个脚本编写重复的事件函数。

修改后的完整代码

HTML文件

<!DOCTYPE html>
<html lang="en">
<head>
  <title>TITLE HERE</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <meta name="viewport">
</head>
<body>
  <div id="LinksList"> 
    <!-- 示例链接,实际由GetLinks.js动态生成 -->
    <a href="javascript:void(0)" data-script="Apple.js" onclick="loadScript(this)">Apple</a>
  </div>
  <div id="ScriptList"> 
  </div>
</body>

<script type="text/javascript" src="GetLinks.js"></script>

<script>
// 缓存已加载的脚本,避免重复请求
const loadedScripts = new Set();

function loadScript(linkElement) {
  const scriptPath = linkElement.dataset.script;
  if (!scriptPath) return;

  // 已加载过则直接执行对应逻辑,不再重复加载
  if (loadedScripts.has(scriptPath)) {
    // 假设脚本暴露的函数为Get+脚本名(如Apple.js对应GetApple)
    const funcName = 'Get' + linkElement.textContent;
    if (typeof window[funcName] === 'function') {
      window[funcName]();
    }
    return;
  }

  // 创建动态script标签
  const script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = scriptPath;

  // 脚本加载成功后的处理
  script.onload = function() {
    loadedScripts.add(scriptPath);
    // 执行脚本对应的初始化函数
    const funcName = 'Get' + linkElement.textContent;
    if (typeof window[funcName] === 'function') {
      window[funcName]();
    }

    // 可选:将JS文件内容插入到ScriptList div中
    // fetch(scriptPath)
    //   .then(res => res.text())
    //   .then(text => {
    //     document.getElementById('ScriptList').textContent = text;
    //   });
  };

  // 脚本加载失败的错误处理
  script.onerror = function() {
    console.error(`加载脚本 ${scriptPath} 失败`);
  };

  // 将script标签添加到页面
  document.body.appendChild(script);
}

window.onload = function() {
  GetLinksList();
};
</script>
</html>

GetLinks.js文件(动态生成链接)

function GetLinksList() {
  const linksContainer = document.getElementById('LinksList');
  // 这里替换成你的实际脚本数据源(比如从后端接口获取)
  const scriptList = [
    { name: 'Apple', path: 'Apple.js' },
    { name: 'Banana', path: 'Banana.js' },
    { name: 'Orange', path: 'Orange.js' }
    // 更多脚本项...
  ];

  scriptList.forEach(item => {
    const link = document.createElement('a');
    link.href = 'javascript:void(0)';
    link.textContent = item.name;
    // 绑定脚本路径到data属性
    link.dataset.script = item.path;
    // 绑定统一的点击事件
    link.onclick = () => loadScript(link);
    linksContainer.appendChild(link);
    // 添加换行分隔(可选)
    linksContainer.appendChild(document.createElement('br'));
  });
}

关键说明

  • 统一逻辑处理:所有链接共用loadScript函数,通过data-script属性传递脚本路径,无需为每个脚本编写单独的GetXxx事件函数。
  • 缓存机制:用loadedScripts集合记录已加载的脚本,避免重复发起网络请求,提升后续点击的响应速度。
  • 动态函数调用:通过链接文本拼接出脚本暴露的函数名(如Apple对应GetApple),实现加载完成后自动执行初始化逻辑。
  • 可选功能:如果需要将JS文件的代码内容展示到ScriptList div中,取消注释onload里的fetch代码即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 12:30:54