Hi guys,
So I've built this mail-program-like HTML viewer (no real emails, just some messages from user to user). It basically behaves just like windows explorer, where you have the labels at the top and the files you can sort by date or alphabetically. Each message looks like this:
<div class="mail_msg" d_id="363">
<div class="done"><img src="../"></div>
<div class="absender">demo</div>
<div class="subject">subject</div>
<div class="name">name</div>
<div class="date">16.09.2010</div>
</div>
Atop of all these messages there is a bar to sort them alphabetically or by date. (using prototypejs)
$$('.absender_label','.subject_label', '.bname_label').each(function(el){
el.observe('click', function(){
/* ... */
var tar = el.className.split('_')[0];
var els = $('widget_mail_'+target).select('.mail_msg'),
sortedEls = els.sort(function(x, y) {
var a = x.down('.'+tar).innerHTML.toLowerCase(),
b = y.down('.'+tar).innerHTML.toLowerCase();
return a < b ? -1 : a > b ? 1 : 0;
});
$('widget_mail_'+target).select('.mail_msg').invoke('remove');
sortedEls.each(function(x){
if(dir=='bottom') {
$('widget_mail_'+target).insert({bottom:x});
} else if(dir=='top') {
$('widget_mail_'+target).down('.mail_msg_label').insert({after:x});
}
});
});
});
I know that there is way too much DOM-manipulation going on. I select all related divs, sort them, throw away all the old unsorted messages and insert the sorted ones at the top or at the bottom (first click from A-Z, second click from Z-A).
It still works with hundreds of messages, but it takes 2 or 3 seconds. I receive the messages as JSON and parse HTML from that, so using a table sorting script like this is not an option at this point.
How can I optimize this sorting?