title: JavaScript : Fastest way to insert DOM element in sort order
body: <p>so I've got several (~30) async calls returning with data (~25 records per call), which I want to display in a specific order.</p>
  
  <p>Currently, the page waits for everything to load, sorts a single internal array, then adds the DOM elements (each item of data is applied to an HTML template/string which is effectively concatenated and added once to the parent element's innerHTML).</p>
  
  <p>I'd LIKE the data to be inserted with each dataset (as it comes back)... but that implies that I need a different way to handle the sort/ordering.</p>
  
  <p>Approaches I've considered:</p>
  
  <ul>
  <li><p>Ideally, mirror the DOM in some sort of B-Tree, so that INSERT operations just traverse the tree looking for the correct element to insertBefore/insertAfter... since I've yet to see any library to address this need, it seems like I'd end up writing a bit of code.</p></li>
  <li><p>manually iterate the DOM looking for the element to insertAfter... seems tediously slow, relatively speaking.</p></li>
  <li><p>just use jQuery.sort(fn) after loading each dataset... seems hacky at best (given the number of times it'd be run, and the volume of DOM manipulation), but by far the easiest to implement code-wise, since it's like 5 lines.</p></li>
  <li><p>I considered some sort of buffer queue between the async returns and the DOM manipulation, but there's far too much that I DON'T know about JS and threading to feel comfortable with that method.</p></li>
  </ul>
  
  <p>I like the idea of inserting directly into the sorted slot, but I am aware that DOM manipulation can be "slow" (depending on how it's done, etc - and I am by no means a JS guru - thus asking here). The idea of the buffer queue with a separate reader/DOM handling seemed like it might provide a reasonable compromise between responsiveness and the DOM manipulation pains, but that's all theoretical for me at this point... and all said and done, if it ends up being more hassle than it's worth, I'll either leave as-is, or just go the lazy route of jQ.sort the DOM.</p>
  
  <p>your knowledgeable advise would be greatly appreciated :)</p>
  
  <p>Thanks</p>