HOWTO · JavaScript
使用 JavaScript 載入外部 HTML 檔案
使用 JavaScript fetch() 或 jQuery load() 載入外部 HTML 片段,並處理伺服器、來源與 HTML 安全方面的考量。
本頁內容
若要將外部 HTML 檔案載入頁面,可用 JavaScript fetch() 發出請求,再將回應插入目標元素;也可以用 jQuery load() 一次完成這兩個步驟。Node.js 範例會在本機伺服器啟動時自動請求片段;瀏覽器範例則會在按鈕點擊後載入 home.html。請透過網頁伺服器提供頁面與片段;以 file: 網址開啟頁面並不會提供網頁請求所需的環境。
使用 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() 不受瀏覽器同源政策限制,因此這項請求並未示範瀏覽器的同源行為。在下方的瀏覽器範例中,相對路徑會以頁面網址為基準解析,這可能與原始檔案所在資料夾不同;若伺服器位於不同來源,必須透過 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 說明。相對請求網址會以頁面網址為基準解析。瀏覽器會實施同源政策;位於其他來源的伺服器必須透過 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() 方法會在按鈕處理程式執行時請求網址,並將回傳的 HTML 放入所選元素。呼叫 $ 的程式碼執行前,必須先成功載入 jQuery。網址仍須能從伺服器連線存取,而跨來源請求仍受瀏覽器來源規則限制。如果頁面原本就依賴 jQuery,可以選用 load();fetch() 則直接使用瀏覽器 API,不需要這個程式庫。此瀏覽器範例的可見介面標籤同樣保持英文不變。