Skip to content

Better way of using jquery’s Append

We use append() method for adding elements dynamically into an already existing element. If you miss use this function, it will dramatically affects the performance of your page.

In this post, I will share a quick performance tip and will show correct way of using jQuery.append().

jQuery.append() inserts content at the end of the each matched element.Here is the basic example, it will append the content into div element

   $("div#test").append("Performance Tip - JQuery Append Outside of Loops");

If you’re appending very less elements to the DOM there is no problem, but If you’re appending a lot of elements to the DOM one by one, instead of appending all elements at a time, than there will be performance smash. Let test it, open you console and run following examples( Assuming that JQuery is available on the console)

Bad way of using –

console.time('loop');
var i = 100;
while ( i-- ) $('body').append(i);
  
console.timeEnd('loop'); 

//output - loop: 95.766ms

Good way of using-

console.time('loop');
var text='';
var i = 100;
while ( i-- ) text +=i; 
  
$('body').append(text);
  
console.timeEnd('loop'); 

//output - loop: 0.651ms

If you observe the time differences of above examples, there is an huge performance improvement with second approach.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments