views:

162

answers:

2

I'm trying to reduce DOM manipulation during my javascript execution, and I thought about lazy-writing DOM elements, versus writing a large section of the DOM hidden and unhiding the needed parts later.

To do this, I've separated out all my DOM content into a JSP which I load into a variable via ajax and manipulate with jQuery. However, if jQuery is doing this manipulation in a hidden div on the DOM, I've achieved no performance gain. Help?

+3  A: 

New Answer

I just checked a couple of your recent questions and I think I see what you're asking here.

When you call jQuery like $('selector string', context) it gets routed to this:

jQuery(context).find('selector string')

do you see that? The context argument becomes the first argument to a [sub] call to jQuery. That in turn gets routed to this batch of shortcut code:

// Handle $(DOMElement)
if ( selector.nodeType ) {
    this[0] = selector;
    this.length = 1;
    this.context = selector;
    return this;
}

so the context argument gets stored on the returned jQuery object in the .context property.

Now judging from your comment to this question, you are aware that you should have your server side code respond with a "Content-Type: text/xml" header. Doing so will instruct the browser to automatically create a DOMDocument tree from your xml response body (FYI it's accessible in the responseXML property on the XMLHttpRequest object itself - jQuery simply passes it on to your success handler).

To answer your question: if you pass this DOMDocument object on to jQuery as the context parameter and proceed to modify attributes on this object, there is no manipulation in any hidden/temporary div that you have to worry about. The DOMDocument is simply mutated in-place.

Hope that answers your question.


Original Answer:

If you have html in a string and you need it to be nodes in a DOM structure, you've got to convert it somehow. Putting it inside a throwaway element is the only way I know to do this while leveraging the built-in browser parser:

// HTML string
var s = '<span>text</span>';

var div = document.createElement('div');
div.innerHTML = s;
var elements = div.childNodes;

Many of the libraries do this more or less, including jQuery. If it makes you feel any better, the throwaway div above is not inserted into the DOM, thereby avoiding DOM reflow (a very expensive operation), saving some cycles.

Crescent Fresh
New answer = $.
Stefan Kendall
+1 - great detective work to piece together the OPs missing bits of knowledge
Russ Cam
@Russ: thanks :) I answered a couple of the OPs questions yesterday so was familiar with his train of thought somewhat.
Crescent Fresh
A: 

You might want to look at document fragments as a container to hold the generated DOM nodes.

var fragment = document.createDocumentFragment();
for ( var e = 0; e < elems.length; e++ ) {
        // append elements to fragment
        fragment.appendChild( elems[e] );
}
Russ Cam