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

如何在getExampleValue函数中动态加载指定JS文件内容?

解决方案

方法1:Fetch 获取脚本内容并在目标上下文执行

这种方式直接拉取JS文件内容,在getExampleValue函数的指定位置执行,不会将脚本插入到body中。

示例代码:

async function getExampleValue(data_option) {
  // ... 函数内其他代码

  // 拼接脚本路径(Django模板渲染时会自动替换{% static %}为实际URL)
  const scriptUrl = "{% static 'js/vis_' %}" + data_option + ".js";

  try {
    // 拉取脚本文本内容
    const response = await fetch(scriptUrl);
    const scriptContent = await response.text();

    // 执行脚本内容(假设脚本内定义了data和layout变量)
    eval(scriptContent);

    // 直接使用脚本中定义的配置渲染图表
    Plotly.newPlot('chart-container', data, layout);
  } catch (error) {
    console.error("加载可视化脚本失败:", error);
  }

  // ... 函数内其他代码
}

优化建议:修改vis_xxx.js的写法,让它直接返回配置对象,避免全局变量污染:

// vis_bar.js 示例写法
({
  data: [{ x: [1,2,3], y: [4,5,6], type: 'bar' }],
  layout: { title: '柱状图示例' }
})

此时执行脚本时可以直接获取配置:

const config = eval(scriptContent);
Plotly.newPlot('chart-container', config.data, config.layout);

方法2:使用ES6动态import(推荐现代项目使用)

如果你的项目支持ES6模块,可以把vis_xxx.js改成模块形式,通过动态import加载,这种方式更安全且符合规范。

首先改造vis_xxx.js为ES模块:

// vis_line.js 示例
export const data = [{ x: [1,2,3], y: [10,20,30], type: 'line' }];
export const layout = { title: '折线图示例' };

然后在getExampleValue中动态加载:

async function getExampleValue(data_option) {
  // ... 函数内其他代码

  try {
    // 动态导入对应模块
    const module = await import("{% static 'js/vis_' %}" + data_option + ".js");
    const { data, layout } = module;

    // 使用配置渲染图表
    Plotly.newPlot('chart-container', data, layout);
  } catch (error) {
    console.error("加载可视化模块失败:", error);
  }

  // ... 函数内其他代码
}

方法3:通过XHR拉取脚本并在局部作用域执行

如果不想用fetch或模块,也可以用XHR拉取脚本内容,通过函数包裹的方式在局部作用域执行:

function loadScriptText(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.onload = () => {
      xhr.status === 200 ? resolve(xhr.responseText) : reject(new Error(`加载失败: ${xhr.status}`));
    };
    xhr.onerror = () => reject(new Error('网络请求失败'));
    xhr.send();
  });
}

async function getExampleValue(data_option) {
  // ... 函数内其他代码

  const scriptUrl = "{% static 'js/vis_' %}" + data_option + ".js";
  try {
    const scriptContent = await loadScriptText(scriptUrl);
    // 创建局部函数执行脚本,避免污染全局
    const getConfig = new Function(`${scriptContent}; return {data, layout};`);
    const { data, layout } = getConfig();

    // 渲染图表
    Plotly.newPlot('chart-container', data, layout);
  } catch (err) {
    console.error(err);
  }

  // ... 函数内其他代码
}

关键注意点

  • 优先使用ES模块方式,减少全局变量冲突,提升代码可维护性
  • 必须处理加载失败的异常,防止函数执行中断影响后续逻辑
  • 确认Django模板已正确渲染{% static %}标签,否则脚本路径会失效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 06:55:25