views:

63

answers:

1

Hello. 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 ?

+1  A: 

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 > *');
Pointy
Thank you, that totally makes sense. Is there a way to efficiently get the elements I am adding ?
nc3b
Won't `$('#some_div > *');` also get the preexisting elements in `#some-div' ?
nc3b
Oh right; sorry, you're appending to the div. I'll fix my answer.
Pointy