Since the DOM tree of a page is active and always reflected in the browser, what is the best way to modify this DOM tree for some purpose without affecting the actual rendered tree ? Let's say my purpose is to swap certain children nodes and see how similar the DOM tree still remains.
Is creating a duplicate tree the only solution ? If it is, is there a function to do this ? Or do I need to write my own function to create a duplicate copy of the tree. I won't need all the attributes of the element object, so I can create a simpler object with a few attributes that point to the siblings and children.
You can use document.cloneNode(true), or the same method on another node. cloneNode clones any node, and the true means it should be recursive (deep). Obviously, this could have a significant performance cost on a large page.
If you are willing to use jQuery:
var clone = $("selectorForSomeElement(s)").clone();
clone now is a copy of the element structure.
You can then work off of clone to do whatever experimenting you like.
Maybe consider one the many great JavaScript librarys out there, e.g. jQuery. These allow you to easily copy parts of or even the whole DOM of an document and have that stored appart from the DOM.
If you need to roll your own solution, a good point to start is Resig's post on document fragments: http://ejohn.org/blog/dom-documentfragments/.
Good luck.
Related
My way of thinking:
If we want to perform something on dom element we can do it by:
document.getElementById("#someId").DoSomething();
document.getElementById("#someId").DoSomethingElse();
In that situation browser needs to search entire DOM for #someId object. Then it forgets element and searches again to perform DoSomethingElse().
To solve "forgetting and searching again" problem we can save our element as JavaScript object.
var someElement = document.getElementById("#someId");
someElement .DoSomething();
someElement .DoSomethingElse();
Going further we can save entire group of elements or entire nodes to achieve better performance. One more step and we have whole DOM saved as an JavaScript object named virtual dom.
Is that correct way to understand purpose of virtual DOM?
Sorry for noob questions, I'm not front end developer, I'm just curious :)
The main point of the VirtualDOM is that, effectively, you're working on a copy of the real DOM. But the working with that copy is ways faster that working with the actual DOM, because it only has the thing that React actually needs, leaving specific browser issues aside.
The main problem with working with the actual DOM is that it's slow. At least, it's faster to work with that kind of copy, make your work there, and the changes have been done, then you update the actual DOM.
Yes, it sounds a bit crazy, but is faster to compute the differences between state changes and the change everything in "just one step", than making that changes with the actual DOM.
Additionally, you've used for your example just a single DOM node, but you're working on changes on DOM subtrees the thing is not that easy.
For an explanation with more detail you can take a look to this article: http://reactkungfu.com/2015/10/the-difference-between-virtual-dom-and-dom/
What is the most efficient way in removing an element in DOM? (js or jquery)
removeChild()
This is what I was using always. But, recently came across this
The removed child node still exists in memory, but is no longer part
of the DOM. With the first syntax-form shown, you may reuse the
removed node later in your code, via the oldChild object reference.
So, If I don't want to preserve the removed element in memory (for better performance), what is the best method?
Or like in java, if reference is null, is it automatically garbage collected and no need to worry about performance? I am asking this specifically as I am dealing with svg and many append/remove calls are made.
I'm currently working on some code for my master's thesis. I've a few questions regarding effective DOM manipulation.
1) Consider you had to perform a bunch of DOM manipulation on a number of nodes that are close to each other. Would it make sense to make a deep copy of the topmost parentNode of all of those nodes (and keep it outside the DOM), perform the manipulations on that subtree and then swap it with it's counterpart in the DOM. Would this minimize browser reflow/re-rendering?
2) Is changing the innerHTML of a node more/less performant than manipulating it's subtree?
3) Is there any more good advice you can give me on efficient DOM manipulation in vanilla javaScript (without any frameworks/libraries)?
Thank you in advance!
The most important thing to do in order to prevent excessive browser rendering is to make sure you group your reads and writes.
If you need to do something to several nodes, and need to read something from them, then you should read from all the nodes first, and then write to all.
The way the DOM works is that each time you need to read from it, it checks if it was changed. If it was, the browser will rerender.
Therefore, first select all the elements, cache the info you need to get, then set on all of them.
1) Consider you had to perform a bunch of DOM manipulation on a number
of nodes that are close to each other. Would it make sense to make a
deep copy of the topmost parentNode of all of those nodes (and keep it
outside the DOM), perform the manipulations on that subtree and then
swap it with it's counterpart in the DOM. Would this minimize browser
reflow/re-rendering?
Yes - do the changes on the counterpart
2) Is changing the innerHTML of a node more/less performant than
manipulating it's subtree?
More performant - because you do the stringmanipulation outside dom
3) Is there any more good advice you can give me on efficient DOM
manipulation in vanilla javaScript (without any frameworks/libraries)?
document.createDocumentFragment() is the best fully controllable virtual dom ever
Say I'm using jQuery to loop through and perform some manipulation on existing web page elements. There are multiple changes to be made, the number of elements in the set is at least somewhat large, and the element structure is somewhat complex.
Assuming I get all the elements into the same jQuery object, would it be faster to use jQuery's .clone (or .detach) method to create an "imaginary" copy to work on, remove the current elements, then re-insert the changed copy into the DOM?
...or does that not make a difference -- as live DOM elements manipulate just as fast as non-DOM ones?
Yes, actually, though your mileage may vary.
When an element is visible, manipulations will cause the browser to redraw the page. Many redraws can add up to a significant performance hit.
When an element is invisible, no redraws will be triggered.
Mass element clones are probably pretty costly, so I'd avoid doing that if possible.
You can clone that object or create a new document fragment. Make changes on that new object and replace it in the DOM:
https://developer.mozilla.org/en-US/docs/Web/API/Node.cloneNode
https://developer.mozilla.org/en-US/docs/Web/API/document.createDocumentFragment
Working on an object that is not part of the DOM will not trigger any paint/reflows.
If performance is an issue do not use jQuery, use plain old Javascript as both cloneNode and createDocumentFragment are well supported.
This question might be stupid, or basic.
Can someone explain which is the best method in adding DOM elements. We have these two ways of adding DOM elements.
Scenario: Need to add <strong>Hi</strong> inside an existing <div id="theEl"></div>.
By editing the HTML inside them.
document.getElementById("theEl").innerHTML = '<strong>Hi</strong>';
By using document.createElement().
var hi = document.createTextNode("Hi"),
strong = document.createElement("strong");
strong.appendChild(hi);
mydiv = document.getElementById("theEl");
document.body.insertBefore(strong, mydiv);
Questions
What is the best way to do? One is a single line, another is about five lines.
What is the performance aspect?
What is the right way or best practise?
Is there any difference between the codes as a whole?
If at all this question is not making sense, please let me know, I will be glad to close this or even remove this. Thanks.
For the close voter, this is not going to be a duplicate of that question. One thing I just noted is, using createElement() preserves the event handlers attached to the element. Even though that's a good point, any kind of basic web page, too has jQuery in them, which provides delegation and such stuff that allow me to have the event attached to the element even after change in HTML.
There is no "best" or "best practice". They are two different methods of adding content that have different characteristics. Which one you select depends upon your particular circumstance.
For creating lots and lots of elements, setting a block of HTML all at once has generally shown to be faster than creating and inserting lots of individual elements. Though if you really cared about this aspect of performance, you would need to test your particular circumstance in a tool like jsperf.
For creating elements with lots of fine control, setting classes from variables, setting content from variables, etc..., it is generally much easier to do this via createElement() where you have direct access to the properties of each element without having to construct a string.
If you really don't know the difference between the two methods and don't see any obvious reason to use one over the other in a particular circumstance, then use the one that's simpler and less code. That's what I do.
In answer to your specific questions:
There is no "best" way. Select the method that works best for your circumstance.
You will need to test the performance of your specific circumstance. Large amounts of HTML have been shown in some cases to be faster by setting one large string with .innerHTML rather than individually created an inserting all the objects.
There is no "right way" or "best practice. See answer #1.
There need be no difference in the end result created by the two methods if they are coded to create the same end result.
I actually like a combination of both: createElement for the outer element so you won't be removing any event handlers, and innerHTML for the content of that element, for convenience and performance. For example:
var strong = document.createElement('strong');
strong.innerHTML = 'Hi';
document.getElementById('theEl').appendChild(strong);
Of course, this technique is more useful when the content of the thing you're adding is more complex; then you can use innerHTML normally (with the exception of the outer element) but you're not removing any event listeners.
1. What is the best way to do? One is a single line, another is about five lines.
It depends on context. You probably want to use innerHTML sparingly as a rule of thumb.
2. What is the performance aspect?
DOM manipulation significantly outperforms innerHTML, but browsers seem to keep improving innerHTML performance.
3. What is the right way or best practise?
See #1.
4. Is there any difference between the codes as a whole?
Yes. The innerHTML example will replace the contents of the existing element, while the DOM example will put the new element next to the old one. You probably meant to write mydiv.appendChild(strong), but this is still different. The existing element's child nodes are appended to rather than replaced.
What did you mean by best? In just one DOM operation everything is good and shows the same performance. But when you need multiple DOM insertion, things go diferently.
Background
Every time you insert DOM node, the browser render new image of the page. So if you insert multiple child inside a DOM node, the browser renders it multiple times. That operation is the slowest that you will see.
The solution
So, we need to append most child at once. Use a empty dom node. The built in is createDocumentFragment();
var holder = createDocumentFragment();
// append everything in the holder
// append holder to the main dom tree
The real answer
If in the case is that you described, I would prefer the shortest solution. Because there is no performance penalty in one dom operation