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?
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: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:so the
contextargument gets stored on the returnedjQueryobject in the.contextproperty.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 aDOMDocumenttree from your xml response body (FYI it’s accessible in theresponseXMLproperty on theXMLHttpRequestobject itself – jQuery simply passes it on to yoursuccesshandler).To answer your question: if you pass this
DOMDocumentobject on to jQuery as thecontextparameter and proceed to modify attributes on this object, there is no manipulation in any hidden/temporarydivthat you have to worry about. TheDOMDocumentis 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:
Many of the libraries do this more or less, including jQuery. If it makes you feel any better, the throwaway
divabove is not inserted into the DOM, thereby avoiding DOM reflow (a very expensive operation), saving some cycles.