Для дальнейшего уточнения моего комментария: часто повторяющаяся вставка элементов в дерево DOM вызывает проблемы с производительностью, поскольку документ должен переформатироваться каждый раз при вставке нового узла. Вам не следует беспокоиться о слишком частом вызове / вызове document.createElement()
: это меньше всего вас беспокоит.
Поэтому я бы посоветовал вам использовать функцию для создания всего элемента семпла. Затем вы можете вызвать эту функцию для создания всего элемента карты по своему усмотрению на каждой итерации l oop, а затем добавить его к фрагменту документа.
Псевдокод:
function createCard() {
// Create the entire `sample element` as you would call it
const el = <something>;
return el;
}
// Create new document fragment to hold all the nodes
// At this point, we are NOT injecting them into the DOM yet
const fragment = new DocumentFragment();
// Go through your data and create new card for each data point
for (let i = 0; i < 5; i++) {
fragment.appendChild(createCard());
}
// Now this is when you insert the entire bulk of the content into the DOM
document.querySelector('#myInsertionTarget').appendChild(fragment);
Код подтверждения концепции выглядит следующим образом:
// Since we are creating so many `<div>` elements
// It helps to further abstract its logic into another function
function createDivElement(classes, text) {
const div = document.createElement('div');
if (classes.length)
div.classList.add(...classes);
if (text)
div.innerText = text;
return div;
}
// Call this whenever you want to create a new card
function createCard(i) {
const colCountry = createDivElement(['col-12', 'p-1'], 'Country');
const colState = createDivElement(['col-3', 'p-1'], 'State');
const colCity = createDivElement(['col-4', 'p-1'], 'City');
const row = createDivElement(['row']);
row.appendChild(colCountry);
row.appendChild(colState);
row.appendChild(colCity);
const cardBody = createDivElement(['card-body']);
cardBody.appendChild(row);
const image = document.createElement('img');
image.alt = 'img';
// Proof-of-concept image source, you can ignore this!
image.src = `https://placehold.it/100x50?text=Image%20${i+1}`;
const imageLink = document.createElement('a');
imageLink.href = '#';
imageLink.appendChild(image);
const card = createDivElement(['card', 'my-3', 'mx-1']);
card.appendChild(imageLink);
card.appendChild(cardBody);
const outer = createDivElement(['col-12', 'col-md-4']);
// outer.style.display = 'none';
outer.appendChild(card);
return outer;
}
// Create new document fragment
const fragment = new DocumentFragment();
// In each iteration of the loop, insert the new card element into fragment
for (let i = 0; i < 5; i++) {
const el = createCard(i);
fragment.appendChild(el);
}
// When you're done generating the entire set of elements
// You can then insert the fragment into your DOM (finally!)
document.querySelector('#app').appendChild(fragment);
<div id="app"></div>