From 719853d2d1886f53288133b1663c5c468d619d05 Mon Sep 17 00:00:00 2001 From: Astrian Zheng Date: Thu, 15 May 2025 14:26:33 +1000 Subject: [PATCH] Enhance %for macro handling: optimize DOM updates by using a document fragment for list rendering --- src/main.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/main.ts b/src/main.ts index 38aa2c5..6a5bd67 100644 --- a/src/main.ts +++ b/src/main.ts @@ -433,6 +433,9 @@ export default (options: ComponentOptions) => { // Clear rendered items renderedItems.length = 0 + // document fragment + const fragment = document.createDocumentFragment() + // Create or update items in the list collection.forEach((item, index) => { // Determine the key for this item @@ -471,10 +474,13 @@ export default (options: ComponentOptions) => { // We will use recursive processing here! this._processElementWithItemContext(itemElement, itemContext) - // Insert the element at the correct position in the DOM - placeholder.parentNode?.insertBefore(itemElement, placeholder.nextSibling) + // Insert the element to the document fragment + fragment.appendChild(itemElement) }) + // Insert the document fragment into the DOM + placeholder.parentNode?.insertBefore(fragment, placeholder.nextSibling) + // Remove any remaining unused items existingElementsByKey.forEach(item => { if (item.element.parentNode) {