Enhance %for macro handling: optimize DOM updates by using a document fragment for list rendering

This commit is contained in:
Astrian Zheng 2025-05-15 14:26:33 +10:00
parent 7ca68b88a4
commit 719853d2d1
Signed by: Astrian
SSH Key Fingerprint: SHA256:rVnhx3DAKjujCwWE13aDl7uV6+9U1MvydLkNRXJrBiA

View File

@ -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) {