4 ms·
> [...] I remember being surprised that there was no way for me to group DOM manipulations into SQL-like transactions [...] There is a way to group DOM manipul
by trebor 10y ago
> [...] I remember being surprised that there was no way for me to group DOM manipulations into SQL-like transactions [...]
There is a way to group DOM manipulations: a DocumentFragment[0]. If you have a wrapper, you can easily use
parent.replaceChild(fragment, wrapper); // [1]
So long as you start with your fragment having a new copy of that wrapper—the entire node and its children will be replaced in 1 operation. Then layout and paint should only happen once apiece.
I've used similar techniques to make applications that render efficiently.
[0]: https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment https://developer.mozilla.org/en-US/docs/Web/API/DocumentFra...
[1]: https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild https://developer.mozilla.org/en-US/docs/Web/API/Node/replac...
- fzzzy 10y agoThat assumes that all the changes are grouped under the same part of the tree...
- trebor 10y agoSure. If you have a ton of potentially layout-thrashing changes, just clone your page's highest wrapper node. Then make your changes and replace the node. I haven't needed it, or tested it for performance, but it's clearly doable. // Example; untested pseudo-code var fragment = document.createDocumentFragment(), wrapper = document.getElementById('wrapper'); fragment.appendChild(wrapper.cloneNode(true)); // update your fragment // update the page document.body.replaceChild(fragment, wrapper); That said, because the change is to a page's entire structure I'd think the layout operation would be much slower. I'm betting React and Ember might do similar things for their "application" wrapper/scope node(s).
- RussianCow 10y agoYou also potentially lose things like focus, input text, and selection on elements that otherwise didn't need to be replaced. I'd wager that re-creating all of that would add a discernible performance cost.