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

JavaScript读取外部HTML文件插入页面 替代字符串拼接实现方案

问题描述

我有一个简易网页,是以iframe形式嵌入在微软Business Central(简称BC)页面中,用来展示地址输入字段,目前我用以下方式把它集成到BC页面:

HTMLContainer.insertAdjacentHTML('beforeend',
  '<div class="addyaddin">' +
  '  <div class="control">' +
  '    <div class="caption">Address</div>' +
  '    <div class="value">' +
  '      <input type="text" class="addressline" id="address1" placeholder="Start typing an address.." auto-complete/>' +
  '    </div>' +
  '  </div>' +

  '  <div class="control">' +
  '    <div class="caption">City</div>' +
  '    <div class="value">' +
  '      <input type="text" id="city" auto-complete/>' +
  '    </div>' +
  '  </div>' +

  '  <div class="control">' +
  '    <div class="caption">Region</div>' +
  '    <div class="value">' +
  '      <input type="text" id="region" auto-complete/>' +
  '    </div>' +
  '  </div>' +
  '</div>');

这段代码可以正常运行,但是需要手动拼接多行HTML字符串,代码杂乱不好维护。我希望可以直接读取独立的外部HTML文件内容存到变量里,再把内容插入到页面,不用在insertAdjacentHTML语句里拼接大量HTML字符串,实现逻辑和下面的伪代码类似:

ReadHtmlFile('\myfile.html',textVariable);
HTMLContainer.insertAdjacentHTML('beforeend',textVariable);

我对JavaScript了解不多,之前的尝试都没成功,希望大家能给我可行的实现指导,谢谢。
Craig


实现方案

你可以用浏览器原生的Fetch API异步加载外部HTML文件,步骤如下:

  1. 先将你之前拼接的HTML片段单独保存为一个独立的模板文件,比如命名为address-template.html,内容就是纯HTML代码,不需要额外的包裹:
<div class="addyaddin">
  <div class="control">
    <div class="caption">Address</div>
    <div class="value">
      <input type="text" class="addressline" id="address1" placeholder="Start typing an address.." auto-complete>
    </div>
  </div>
  <div class="control">
    <div class="caption">City</div>
    <div class="value">
      <input type="text" id="city" auto-complete>
    </div>
  </div>
  <div class="control">
    <div class="caption">Region</div>
    <div class="value">
      <input type="text" id="region" auto-complete>
    </div>
  </div>
</div>
  1. 把你原来拼接HTML的JS代码替换为下方代码即可:
// 加载外部HTML模板
fetch('address-template.html')
  .then(response => {
    if (!response.ok) throw new Error('模板加载失败,状态码:' + response.status);
    return response.text();
  })
  .then(htmlContent => {
    // 拿到模板内容后插入到容器
    HTMLContainer.insertAdjacentHTML('beforeend', htmlContent);
    // 如果需要给地址输入框绑定事件,可在此处编写代码,此时对应的DOM元素已生成
  })
  .catch(error => {
    console.error('加载模板出错:', error);
  });

注意事项

  • 不要直接双击本地HTML文件测试,浏览器的跨域安全规则会禁止读取本地磁盘文件,你需要将代码部署在HTTP服务上运行,本地开发可以用VS Code的Live Server插件快速启动测试服务
  • 如果模板文件放在其他目录,修改fetch方法中的路径即可,比如模板存放在templates目录下,就写成fetch('templates/address-template.html')
  • 如果你需要绑定加载完成后的后续逻辑,全部放在第二个then回调中即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 00:18:03