Recently, I developed a HTML viewer resembling a mail program interface (though without actual emails, just user messages). The layout mimics Windows Explorer with labels at the top and messages that can be sorted by date or alphabetically. Here's an example of what each message looks like:
<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>
Above these messages, there is a sorting bar allowing users 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 am aware that there is a substantial amount of DOM manipulation happening here. I select all relevant divs, sort them, discard the unsorted messages, and then insert the sorted ones either at the top or bottom based on user preference (first click sorts A-Z, second Z-A).
This process still functions relatively smoothly even with hundreds of messages, although it does take about 2-3 seconds. Since I receive the messages as JSON and extract HTML from them, using a table sorting script like this isn't a viable option at this stage.
How can I enhance the efficiency of this sorting method?