Heavy DOM manipulation performance - javascript

I'm doing heavy DOM manipulation in JS.
What I do today is creating element (not linking it to document) - perform all heavy stuff on that element, when all completed, linking it to document.
I assume this should be fine - as element is not linked to document during manipulations.
However I reviewed several topics on that, and people were talking there about using:
documentFragment
display = none
Is that anything I should consider, or it's equivalent to what I already do.
Is there any advantage of creating documentFragment over creating regular element as I do?
Any good articles you can propose on that topic?
Thanks!

Related

Potential performance improvement from inserting chunks of DOM elements dynamically as needed?

I'm looking at ways to improve performance of my single page web app, which will need to run on a variety of devices including lower-end phones.
I've got 8 modals (Twitter Bootstrap but this question applies to any framework) that add over 200 elements to my total page DOM element count (783). Is it worth having these as strings in Javascript rather than code in the HTML, and injecting them when needed into the DOM immediately before display, then removing them afterward? Would strip live DOM size down by a quarter, thus making e.g. JQuery element searches quicker, lighterweight page etc.
I was thinking to use JQuery's $.detach() and $.append() for example
Anytime you modify the DOM, you take a performance hit because the browser will have to "reflow" and "repaint" the UI. As such, keeping those modifications to a minimum will help, however doing modifications in batches absorbs some of that performance hit (i.e. changing 3 DOM elements separately is more expensive than changing all 3 at once). So, group together your DOM changes as best you can.
The actual mechanism you use to inject the new content could either be by:
Passing a string of HTML to the HTML parser and asking it to parse
on demand the string. This is essentially the same as the process
that happens when the page is being parsed from the server. Using
the standard .innerHTML or JQuery .html() accomplishes this.
You could also build up the DOM element in memory first and then
inject that node into the DOM at the right time (i.e. document.createElement or document.createDocumentFragment). I generally favor
this approach as it is more programmatic, vastly reduces the
possibility of string concatenation and quotation errors and is
cleaner to read. From a performance standpoint, this gives you the
benefit of getting some of the work done prior to DOM injection
time. This would be the equivalent of the DOM .appendChild() or
the JQuery .append() methods.
In the end, today's modern user agents handle DOM changes much better than they used to and either approach is viable. It's the really bad techniques (like modifying the DOM in a loop) that you want to stay away from that, in the end, will make a difference.

JavaScript - DOM Manipulation - Is construction a page first then attaching?

New to javascript...and dom manipulation...Let's say I'm using java-script to construct part of a page that has a bunch of sub-elements.
<div>my-sub-elements</div>
Should I create a stand-alone-div attach the elements inside then attach the whole thing to the DOM?
Or should I attach the elements one by one to the DOM?
You usually will not be able to notice a difference, but in case you really need it then constructing a detached DocumentFragment and attaching it in a single step is faster than messing with the live DOM tree many times.

Delineating a section of HTML without altering document flow

I'm working on a web application that requires me to transparently delineate a section of the DOM for usage with JavaScript. The issue is that I don't necessarily know what the rest of the page markup will look like.
I do know that the markup within the section will be 'self-contained' in that tags started within the section will also end within the section and vice versa.
I could play it safe and use comments at the start and end of the section, but this makes it somewhat inconvenient to play with in JavaScript. I'd rather be able to use DOM manipulation functions to find and modify this section.
So I guess my question is, do 'inline' elements modify the document flow at all? (Without special CSS rules) I'd like the document to look exactly the same if the tags delineating the section weren't present.
If an inline element does alter the document flow, is there a way to make an element that can be recognised by JavaScript but does not alter the document flow?
Thanks,
YM
P.S. Cross-browser support and standards compliance are important to me on this one.
EDIT: Quick note that I'm not just being lazy here. I have conducted tests and research about this and so far I believe inline elements don't alter the flow at all. (Unless they are told to with CSS) The purpose for this question is the ensure that these observations are correct and to discover any possible scenarios under which this doesn't hold true.
EDIT2: As the comments pointed out, I don't quite seem to have the vocabulary to accurately describe what I'm asking for. I also believe this question may be subjective, so I think I'll just close it and use the data tags method provided below.
Yes, inline elements are part of the document flow. Inline elements don't start with a new line but they can flow to additional lines if their contents are too large.
It sounds like you're writing some sort of visual JS code inspector. You could target your HTML elements with JS with data-* attributes, which will not impact your CSS or flow.

Faster to append or create html elements before? -- JQuery

I am trying to make my application faster. I want some elements to appear only when an ajax request has succeeded. Is it faster to create the elements with append when the request has succeeded, or is it faster to create the html element in the actual html and simply insert the content in the element with .html?
According to this JSPerf: plain old innerHTML beats .html() (and .html() beats .append()).
However according to this JSPerf: DOM beats innerHTML.
So, might want to look into documentFragment, specified in DOM1 and even supported in IE6 (so there is no reason not to use it).
Since the document fragment is in memory and not part of the main DOM tree, appending children to it does not cause page 'reflow' (computation of element's position and geometry). Consequently, using document fragments often results in better performance.
John Resig did a nice write-up about it here and concludes:
A method that is largely ignored in modern web development can provide
some serious (2-3x) performance improvements to your DOM manipulation.
You just might want to combine some of those techniques per case you want to optimize.
Hope this helps!

removing unused DOM elements for performance

I'm writing a single page application. When the page is initially served, it contains many DOM elements that contain json strings that I'm injecting into the page.
When the page loads on the client, the first thing that happens is that these DOM elements are parsed from json to javascript objects and then they're never used again.
Would there be a performance benefit into deleting them from the DOM and reducing its size? I haven't found any conclusive data about this aspect. For info, these elements are about 500K in size.
Thanks for your suggestions.
Would there be a performance benefit into deleting them from the DOM
and reducing its size?
In terms of the performance of the DOM, generally, the less you interact with your DOM, the better.
Remember that your selectors traverse the dom, so if you use inefficient selectors, it will be poor performance no matter what, but if you're selecting elements by ID rather than class or attribute wherever possible, you can squeeze good performance out of the page, regardless of whether you've deleted those extraneous markup items.
When the page is initially served, it contains many DOM elements that
contain json strings that I'm injecting into the page.... For info,
these elemnts are about 500K in size.
In terms of page load, your performance is suffering already from having to transfer all of that data. if you can find a way to transfer the json only, it could only help. Deleting after the fact wouldn't be solving this particular problem, though.
Independent of whether you pull the JSON from the DOM, you might consider this technique for including your JSON objects:
<script type='text/json' id='whatever'>
{ "some": "json" }
</script>
Browsers will completely ignore the contents of those scripts (except of course for embedded strings that look like </script>, which it occurs to me as things a JSON serializer might want to somehow deal with), so you don't risk running into proplems with embedded ampersands and things. That's probably a performance win in and of itself: the browser probably has an easier time looking for the end of the <script> block than it does looking through stuff that it thinks is actual content. You can get the content verbatim with .innerHTML.

Categories

Resources