萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

JavaScript 動態插入 HTML 標籤實戰:insertAdjacentHTML、DOM API 與 XSS 防護

動態插入 HTML 的四大核心 API

現代前端開發頻繁需要動態插入標籤:無限滾動載入、即時搜尋結果、表單動態增欄、模態框內容注入。選擇正確 API 能兼顧效能、安全與維護性。

API 對照表

方法插入位置回傳值效能安全性適用場景
insertAdjacentHTML(position, html)beforebegin, afterbegin, beforeend, afterendundefined⚡ 快(單次解析)⚠️ 需自行淨化大量 HTML 片段插入、指定精確位置
element.innerHTML = html替換全體子內容undefined⚡ 快⚠️ 需自行淨化整區塊重渲染
element.append(...nodes)子節點末尾undefined🔄 中(建立節點)✅ 安全(文字節點不解析)動態建立元素、避免 XSS
element.prepend(...nodes)子節點開頭undefined🔄 中✅ 安全新增至列表開頭
element.before(...nodes)元素之前(同層)undefined🔄 中✅ 安全插入同級元素
element.after(...nodes)元素之後(同層)undefined🔄 中✅ 安全插入同級元素
element.replaceWith(...nodes)替換元素本身undefined🔄 中✅ 安全元素替換

insertAdjacentHTML 位置圖解

<div id="container">
  <!-- beforebegin -->
  <div>
    <!-- afterbegin -->
    <p>現有內容</p>
    <!-- beforeend -->
  </div>
  <!-- afterend -->
</div>

安全第一:插入前必須淨化

// ❌ 危險:直接插入使用者輸入
container.insertAdjacentHTML('beforeend', userInput);

// ✅ 安全:DOMPurify 淨化後插入
import DOMPurify from 'dompurify';
const cleanHTML = DOMPurify.sanitize(userInput, {
  ALLOWED_TAGS: ['p', 'br', 'b', 'i', 'strong', 'em', 'a'],
  ALLOWED_ATTR: ['href', 'target', 'rel']
});
container.insertAdjacentHTML('beforeend', cleanHTML);

// ✅ 更安全:使用 DOM API 建立節點(完全避免 HTML 解析)
function createSafeElement(tag, attributes = {}, ...children) {
  const el = document.createElement(tag);
  Object.entries(attributes).forEach(([key, value]) => {
    if (key.startsWith('on')) return; // 拒絕事件屬性
    el.setAttribute(key, value);
  });
  children.forEach(child => {
    if (typeof child === 'string') {
      el.appendChild(document.createTextNode(child));
    } else if (child instanceof Node) {
      el.appendChild(child);
    }
  });
  return el;
}

// 使用
const link = createSafeElement('a', { href: url, target: '_blank', rel: 'noopener' }, '連結文字');
container.append(link);

效能優化:DocumentFragment 批次插入

function appendManyItems(container, items) {
  const fragment = document.createDocumentFragment();
  
  items.forEach(item => {
    const div = document.createElement('div');
    div.className = 'item';
    div.textContent = item.text; // 純文字,安全
    fragment.appendChild(div);
  });
  
  // 單次重排/重繪
  container.appendChild(fragment);
}

// 虛擬滾動配合:只渲染可視區
// 推薦使用 @tanstack/virtual, react-window, vue-virtual-scroller

進階:HTML Template 元素預編譯

<template id="item-template">
  <article class="card">
    <h3 class="title"></h3>
    <p class="desc"></p>
    <a class="link" href="#">閱讀更多</a>
  </article>
</template>

function renderItem(data) {
  const template = document.getElementById('item-template');
  const clone = template.content.cloneNode(true); // DocumentFragment
  
  clone.querySelector('.title').textContent = data.title;
  clone.querySelector('.desc').textContent = data.description;
  clone.querySelector('.link').href = data.url;
  
  return clone;
}

// 批次渲染
const fragment = document.createDocumentFragment();
dataList.forEach(item => fragment.appendChild(renderItem(item)));
container.appendChild(fragment);

框架整合建議

  • React/Vue/Svelte:使用框架內建渲染機制(JSX/模板/編譯輸出),**避免直接操作 DOM**
  • Alpine.js / Stimulus / vanilla JS:善用 <template> + cloneNode + textContent 模式
  • jQuery 專案:$(html).appendTo(container) 內部用 innerHTML,**務必先 DOMPurify**

除錯技巧

// 監聽所有 DOM 插入(開發模式)
const observer = new MutationObserver(mutations => {
  mutations.forEach(m => {
    if (m.type === 'childList' && m.addedNodes.length) {
      console.log('新增節點:', m.addedNodes);
    }
  });
});
observer.observe(document.body, { childList: true, subtree: true });

動態插入 HTML 以 DOM API(append/prepend/textContent)為首選(天然安全),大量 HTML 片段用 insertAdjacentHTML + DOMPurify,超大列表採用 DocumentFragment + 虛擬滾動,