jQuery .load(url, [data], [callback]) 是將遠程 HTML 片段插入指定元素的最簡單方法。本文詳細說明參數、回調時機、腳本執行機制、常見坑點及現代替代方案。
$(selector).load(url, [data], [callback]);
"page.html #fragment" 僅提取片段。status 為 success/error/notmodified。<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>jQuery load 示例</title>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
</head>
<body>
<button id="btnLoad">加載側邊欄</button>
<div id="top_sidebar" style="border:1px dashed #ccc; min-height:100px;">內容將在這裡顯示</div>
<script>
$('#btnLoad').on('click', () => {
$('#top_sidebar').load('top_sidebar.html', (resp, status, xhr) => {
if (status === 'error') {
console.error('加載失敗:', xhr.status, xhr.statusText);
$('#top_sidebar').html('加載失敗,請重試');
} else {
console.log('加載成功');
}
});
});
</script>
</body>
</html>
// 僅獲取 top_sidebar.html 中 id="nav" 的內容
$('#top_sidebar').load('top_sidebar.html #nav');
這避免了整頁 HTML(含 <head>、<script> 等)污染當前頁面。
$('#result').load('search.html', {q: '關鍵詞', page: 2});
// 實際發送 POST /search.html?q=關鍵詞&page=2
<script> **會被執行**,但**不會保留在 DOM 中**(jQuery 內部用 .append() 後移除 script)。eval 或改用 $.ajax({dataType:'html'}) 手動處理。| 現象 | 原因 | 解決 |
|---|---|---|
| 樣式失效/衝突 | 片段含 <style> 或全局類名 | 片段使用 Scoped CSS / CSS Modules / BEM 命名;或用 Shadow DOM 隔離 |
| 重複綁定事件 | 多次 .load() 同一容器,舊腳本未銷毀 | 回調前先 .off() 或用事件委託 $(document).on('click', '.btn', ...) |
| 跨域報錯 | 瀏覽器同源策略 | 後端配置 CORS Access-Control-Allow-Origin;或同域部署/反向代理 |
| 中文亂碼 | 服務端未聲明 Content-Type: text/html; charset=utf-8 | 後端設置 charset;或前端 .load(url + '?t=' + Date.now()) 防緩存 |
腳本報錯 $ is not defined | 片段依賴 jQuery 但當前頁未引入/版本衝突 | 確保主頁引入 jQuery,片段勿重複引入 |
async function loadHTML(selector, url, fragment = '') {
const el = document.querySelector(selector);
try {
const resp = await fetch(url);
if (!resp.ok) throw new Error(resp.statusText);
const html = await resp.text();
const doc = new DOMParser().parseFromString(html, 'text/html');
const content = fragment ? doc.querySelector(fragment) : doc.body;
el.innerHTML = content?.innerHTML || '';
// 手動執行腳本
el.querySelectorAll('script').forEach(s => {
const ns = document.createElement('script');
[...s.attributes].forEach(a => ns.setAttribute(a.name, a.value));
ns.textContent = s.textContent;
s.replaceWith(ns);
});
} catch (e) {
el.innerHTML = `加載失敗: ${e.message}`;
}
}
// 用法
loadHTML('#top_sidebar', 'top_sidebar.html #nav');
import('./Sidebar.vue') 或路由懶加載,避免字符串模板注入。<slot> 或 Server Components 組合片段。.load() 適合**老舊 jQuery 專案**快速接入靜態/動態片段。.load(),務必:片段化選擇器、事件委託、錯誤兜底、編碼聲明。