Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery appending html versus appending existing element

I have a string big_html and I want to add it to some div. I have observed a performance difference in the following:

$('#some-div').append( big_html );
// takes about 100 ms

//create it first
var append_objs = $(big_html);
$('#some-div').append( append_objs );
//takes about 150 ms

Does anyone know why this happens ? Thank you for your time.

EDIT: I am trying to get the stuff I am adding to the page. I have also tried

var added = $(big_html).appendTo( '#some-div' );
//150 ms

Is there an efficient way to do this ?

like image 795
nc3b Avatar asked Jul 15 '10 13:07

nc3b


1 Answers

In the second case, jQuery has the browser build a document fragment and then it stuffs the HTML in that for the browser to parse. Then, you have it manipulate the DOM again when you append that to your page.

Thus the second version is simply doing more work than the first.

I encourage you (and everybody interested) to keep the non-minified version of jQuery around for perusal. It's enlightening to just read through the code.

To "get" your content after it's added to the DOM sort-of depends on what it is. Since the content is being appended, you sort-of have to start off by remembering the last element of the target:

var last = $('#some_div > *:last');
$('#some_div').append(big_html_string);
var newStuff = last.nextAll();

If the target div might start empty, you'd need to check for that too:

var newStuff = last.length ? last.nextAll() : $('#some_div > *');
like image 105
Pointy Avatar answered Sep 18 '22 19:09

Pointy