承接上文,本文通過具體場景深入對比 appendChild 與 insertBefore 在插入位置控制、批量插入效能、DocumentFragment 應用上的具體差異,並給出決策指南。
// 簡潔、語意清晰
list.appendChild(newItem);
// 現代寫法
list.append(newItem);
// 在 refNode 之前插入
parent.insertBefore(newNode, refNode);
// 實際案例:按字母序插入
function insertSorted(parent, newNode, getKey) {
const children = [...parent.children];
const key = getKey(newNode);
const ref = children.find(c => getKey(c) > key) || null;
parent.insertBefore(newNode, ref); // ref 為 null 時自動追加到末尾
}
// ❌ 差:每次 appendChild 觸發重排
items.forEach(item => ul.appendChild(createLi(item)));
// ✅ 優:DocumentFragment 離線構建,一次掛載觸發一次重排
const frag = document.createDocumentFragment();
items.forEach(item => frag.appendChild(createLi(item)));
ul.appendChild(frag);
// ✅ 現代:append 接受多參數,內部同樣優化
ul.append(...items.map(createLi));
const item = document.getElementById('item-3');
otherList.appendChild(item); // 從原父節點移除,插入新父節點末尾
// 等同於
otherList.insertBefore(item, null);
| 需求 | 推薦方法 | 理由 |
|---|---|---|
| 尾部追加單節點 | appendChild / append | 語意明確、簡潔 |
| 頭部插入 | prepend / insertBefore(node, firstChild) | 現代 API 更直觀 |
| 任意位置插入 | insertBefore / before/after | 需參考節點 |
| 批量插入 | DocumentFragment + appendChild 或 append(...nodes) | 減少重排 |
| 移動現有節點 | 任意插入方法均可 | 節點自動移除 |
insertBefore 的參考節點**必須是目標父節點的直接子節點**,否則拋錯。<template> 內容需先 template.content.cloneNode(true) 再插入。document.createElementNS 創建,插入邏輯相同。