Reputation: 38199
I'm optimizing a bottleneck that, not surprisingly, is the result of tens of thousands of appends in a loop.
I'm familiar with the pattern of accumulating new elements as strings, then joining and inserting them in a single append. But what if those elements have text content that needs to be escaped, i.e. would normally be set using .text()
?
I'm currently creating these as separate elements, appending them to a container outside the DOM, then inserting that container. Is there a faster approach?
Upvotes: 0
Views: 90
Reputation: 4615
Use the accumulation-as-string method. If you need to simulate the text()
method, use the shown escapeText
method like this:
var escapeText = function(s)
{
return s.split('&').join('&').split('<').join('<').split('>').join('>').split('"').join('"');
};
var someArray = ....
var toInsert = '';
for (var i=0; i<someArray.length; i++)
{
toInsert += '<p>' + escapeText(someArray[i]) + '</p>';
}
$('#foo').append(toInsert);
Upvotes: 1