8

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 Answer 1

4

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 > *');
Sign up to request clarification or add additional context in comments.

3 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.