在一個 HTML 頁面中嵌入另一個 HTML 頁面,標準方案是 `
<iframe src="top1.html" frameBorder="0" width="900" scrolling="no" height="90"></iframe>
<span id="show"></span>
<!-- IE 專有 XML 命名空間元素 -->
<IE:Download ID="oDownload" STYLE="behavior:url(#default#download)" />
<script>
function onDownloadDone(downDate) {
show.innerHTML = downDate; // 將下載內容直接注入
}
oDownload.startDownload('b.htm', onDownloadDone);
</script>
機制:異步下載 HTML 片段,回調中注入容器。類似早期 AJAX (`XMLHttpRequest` 前身)。
缺陷:僅 IE 支持、無樣式隔離 (CSS 污染)、腳本執行上下文混亂、無安全沙箱、無緩存控制。
<div id="embed-container"></div>
<script>
async function embedHTML(url, containerId) {
try {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const html = await response.text();
const container = document.getElementById(containerId);
// 安全:DOMPurify 淨化 (防 XSS)
// container.innerHTML = DOMPurify.sanitize(html);
container.innerHTML = html; // 信任來源時
// 執行內部腳本 (需手動)
container.querySelectorAll('script').forEach(oldScript => {
const newScript = document.createElement('script');
Array.from(oldScript.attributes).forEach(attr =>
newScript.setAttribute(attr.name, attr.value));
newScript.textContent = oldScript.textContent;
oldScript.parentNode.replaceChild(newScript, oldScript);
});
} catch (err) {
console.error('嵌入失敗:', err);
document.getElementById(containerId).innerHTML =
'<div class="error">內容加載失敗</div>';
}
}
embedHTML('top1.html', 'embed-container');
</script>
| 維度 | iframe | Behavior download | Fetch + innerHTML |
|---|---|---|---|
| 瀏覽器支持 | 所有 | 僅 IE | 現代瀏覽器 |
| 樣式隔離 | ✅ 完全隔離 | ❌ 污染父頁 | ❌ 污染父頁 (需 Shadow DOM/iframe) |
| 腳本隔離 | ✅ 獨立上下文 | ❌ 共享上下文 | ❌ 共享上下文 |
| 安全沙箱 | ✅ sandbox 屬性 | ❌ 無 | ❌ 需 DOMPurify |
| 跨域支持 | ✅ (受限/通信) | ❌ 同域限制 | ✅ (CORS) |
| SEO | ❌ 內容不被索引 | ✅ 內容在頁面 | ✅ 內容在頁面 |
| 推薦度 | ⭐⭐⭐⭐⭐ | ⭐ (歷史) | ⭐⭐⭐ (同域片段) |