DOM Manipulation yang Efisien
Manipulasi DOM adalah salah satu operasi paling mahal di browser. Setiap perubahan DOM bisa trigger layout recalculation (reflow) dan repaint.
Batch DOM Reads & Writes
Layout thrashing terjadi saat kita bergantian baca dan tulis DOM:
// BURUK — layout thrashing (force reflow setiap iterasi)
elements.forEach(el => {
const height = el.offsetHeight; // READ → force layout
el.style.height = height + 10 + "px"; // WRITE → invalidate layout
});
// BAIK — batch reads, then batch writes
const heights = elements.map(el => el.offsetHeight); // batch READ
elements.forEach((el, i) => {
el.style.height = heights[i] + 10 + "px"; // batch WRITE
});
DocumentFragment
Saat menambahkan banyak elemen, gunakan DocumentFragment untuk menghindari multiple reflows:
// BURUK — 1000 reflows
for (let i = 0; i < 1000; i++) {
const li = document.createElement("li");
li.textContent = "Item " + i;
list.appendChild(li); // reflow setiap append
}
// BAIK — 1 reflow
const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
const li = document.createElement("li");
li.textContent = "Item " + i;
fragment.appendChild(li);
}
list.appendChild(fragment); // 1 reflow saja
innerHTML vs createElement
Untuk insert banyak elemen sekaligus, innerHTML sering lebih cepat karena browser bisa parse HTML secara batch. Tapi hati-hati dengan XSS!