views:

41

answers:

2

I'm building a jQuery UI widget and when I initialize I create a several divs, anchors, inputs. I've read that it's faster to build up an entire HTML string and then append it to the DOM than to append each individual DOM element.

However, I need access to those elements later, so I'm also inclined to build them individually and then append them so I already have them cached rather than selecting them after I append all the HTML.

What is generally faster?

e.g.:

var html = $('<div id="container">.....several more divs, anchors and inputs all with IDs......</div>');

<dom element>.append(html);
this.container = $('#container');
this.search = $('#search');
...and so on

or

this.container = $('<div id="container"></div>');
this.search = $('<input .... id="search" />');
...and the rest of the divs, anchors and inputs then...

<dom element>.append(this.container).append(this.search) ..... and so on
A: 

This create a DOM fragment which is pretty quick, creating a lot of them will be slower.

var html = $('<div id="container">.....several more divs, anchors and inputs all with IDs......</div>');

you can speed up the selectors by giving it the limited context that you know that the elements are in.

this.container = html; //since #container is the top div in html, html = #container
this.search = html.find('#search');

And then finally add to the DOM This is the append that is slow because it causes the browser to redraw.

<dom element>.append(html);

This will get you want you want without having to create multiple DOM fragments which will be slower.

PetersenDidIt