HOWTO · JavaScript

使用 JavaScript 加载外部 HTML 文件

使用 JavaScript fetch() 或 jQuery load() 加载外部 HTML 片段,并处理服务器、来源和 HTML 安全方面的注意事项。

本页内容

要将外部 HTML 文件载入页面,可以使用 JavaScript fetch() 发出请求,再把响应内容插入目标元素;也可以用 jQuery load() 一次完成这两步。Node.js 示例会在本地服务器启动时自动请求片段;浏览器示例则会在点击按钮后载入 home.html。请通过 Web 服务器提供页面和片段;使用 file: URL 打开页面并不会建立可供网页请求使用的环境。

使用 JavaScript fetch() 方法载入外部 HTML 文件

以下 Node.js 示例会启动本地 HTTP 服务器,使用 fetch() 请求 HTML 片段,并输出响应正文。它展示了如何发出请求并将响应转换为文本;下方的浏览器页面示例则说明如何把这段文本放入 DOM。

const http = require("node:http");

const server = http.createServer((request, response) => {
  response.writeHead(200, { "Content-Type": "text/html" });
  response.end("<p>Loaded fragment</p>");
});

server.listen(0, "127.0.0.1", async () => {
  try {
    const { port } = server.address();
    const response = await fetch(`http://127.0.0.1:${port}/home.html`);
    console.log(await response.text());
  } catch {
    console.log("Request failed");
  } finally {
    server.close();
  }
});
<p>Loaded fragment</p>

服务器会选择一个可用端口,并通过回环地址在 /home.html 提供片段。Node.js fetch() 不受浏览器同源政策限制,因此这项请求并未展示浏览器中的同源行为。在下方的浏览器示例中,相对路径会以页面 URL 为基准解析;该 URL 对应的位置可能与源文件所在的资料夹不同。如果服务器位于不同来源,则必须通过 CORS 允许此请求。

将此片段保存为 home.html,并放在要载入它的页面旁边:

<p>This content is loaded from the home page.</p>

在页面中加入按钮、内容目标元素和状态显示区域。该浏览器示例的可见界面标签保持英文不变。下方的点击处理程序使用浏览器原生的 fetch('./home.html');请求失败时会在页面中显示错误,响应成功后则插入返回的片段:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Load an HTML fragment</title>
  </head>
  <body>
    <button type="button" id="loadHome">Load home content</button>
    <p id="loadStatus" role="status"></p>
    <div id="homePage"></div>
    <script>
      const button = document.querySelector('#loadHome');
      const target = document.querySelector('#homePage');
      const status = document.querySelector('#loadStatus');

      button.addEventListener('click', async () => {
        status.textContent = 'Loading…';

        try {
          const response = await fetch('./home.html');
          if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
          }

          target.innerHTML = await response.text();
          status.textContent = 'Content loaded.';
        } catch (error) {
          status.textContent = 'Could not load the content. Check the server and try again.';
          console.error('HTML fragment request failed:', error);
        }
      });
    </script>
  </body>
</html>

处理程序会检查 response.ok,因为 fetch() 只会在网络故障时拒绝 Promise,不会仅因服务器返回 HTTP 错误状态而拒绝;response.text() 会将响应正文读取为文本。请参阅 MDN 的 fetch() 文件和 Response.ok 文件。相对请求 URL 会以页面 URL 为基准解析。浏览器会执行同源政策;位于其他来源的服务器必须通过 CORS 允许此请求。由于 innerHTML 会将返回的字符串解析为标记,只应插入可信内容;请参阅 MDN 关于 innerHTML 的安全指南。上方的页面源码是浏览器示例,提供的运行时证据并未执行它;该证据验证的是 Node.js 服务器示例。

使用 jQuery load() 方法载入外部 HTML 文件

沿用上方相同的 home.html 片段。在自己的脚本之前载入 jQuery,然后为元素加入点击处理程序。以下静态页面源码展示了所需的设置和互动方式;它并不是已执行的浏览器示例:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
  </head>
  <body>
    <button type="button" id="loadHome">Load home content</button>
    <div id="homePage">Click the button to load the fragment.</div>
    <script>
      $('#loadHome').on('click', function () {
        $('#homePage').load('./home.html');
      });
    </script>
  </body>
</html>

点击处理程序运行时,load() 方法会请求该 URL,并将返回的 HTML 放入选定元素。调用 $ 的代码执行前,必须先成功载入 jQuery。服务器也必须能提供此 URL;跨来源请求仍受浏览器来源规则限制。如果页面已经依赖 jQuery,可以选择 load();fetch() 则直接使用浏览器 API,不需要该函式库。此浏览器示例的可见界面标签同样保持英文不变。