javascript - How can I sort DOM elements triggering the least amount of reflow? -
i've got following example.
<div class="parent"> <div data-id="5"></div> <div data-id="2"></div> <div data-id="3"></div> <div data-id="1"></div> <div data-id="4"></div> </div>
if want order these div's in ascending order (1,2,3,4,5). loop , append div's in order parent
div. mean always make 5 changes dom (regardless of order of div's), 1 each div.
you can use .insertbefore() method order div's correctly 2 changes!
5,2,3,1,4 insert 1 before 2 5,1,2,3,4 insert 5 behind 4 (using .insertbefore() , .nextsibling) 1,2,3,4,5
question 1 making 2 changes dom assume less reflow ocours, making '2 change' sorting action faster '5 change'sorting action. correct?
question 2 sort of method/algorithm able figure out insert 1 before 2
, 5 behind 4
?
question 3 (bonus) 'optimized' algorithm still faster amount of items incease? range 10 - 100 - 1.000 - 10.000 - 100.000
maybe clarify: not searching way figure out order (1,2,3,4,5) in optimal way. @ point know order want compare order agains order of div's , figure out least amount of operations.
be more confident in browsers’ capabilities.
browsers batch dom operations when performed in 1 single, synchronous execution of javascript sequence. exceptions occur when explicitely (and unknowingly) request reflow accessing dom properties/methods require dom up-to-date, e.g.
innerwidth
,offsettop
, orgetboundingclientrect
. see rendering: repaint, reflow, restyle details.
deleting dom nodes not necessary. add them newly createddocumentfragment
, they’ll automatically removed current position in dom.browsers, more js engines, know , use smartest sorting algorithm. save specific cases, don’t need know inner mechanisms of sorting operation. use
array.prototype.sort
, provide custom function if necessary, , watch magic happen.
Comments
Post a Comment