[jQuery] Some more findings concerning speed - $.tabs optimized
Hi all,
I now have optimized the $.tabs plugin with some interesting results.
Before the optimization changing the tab took about 250ms, which in my
eyes was unacceptabel because of a noticeable delay after the click (a
co-worker indeed once asked me, if the content of the tab is fetched via
XmlHttp...)
So I rewrote the code using the '#' selector (assuming that this would
use the faster getElementById() at once) - Example: Instead of
$("[@id='" + containerId + "']/div:visible").hide();
I now use:
$(id + '>div:visible').hide();
where id is a string like '#givenId'
After making these changes changing the tab took maximum 16ms! Now I
feel much better :-)
You may notice the difference if you take a look at these two pages
http://stilbuero.de/demo/jquery/tabs.html (fast)
http://stilbuero.de/demo/jquery/tabs_old.html (slow)
though it was much more apparent for the site I am working on at the
moment. I guess this was caused by the much larger DOM tree jQuery had
to parse...
The optimized code:
$.tabs = function(containerId, start) {
var ON_CLASS = 'on';
var id = '#' + containerId;
var i = (typeof start == "number") ? start - 1 : 0;
$(id + '>div:lt(' + i + ')').add(id + '>div:gt(' + i + ')').hide();
$(id + '>ul>li:nth-child(' + i + ')').addClass(ON_CLASS);
$(id + '>ul>li>a').click(function() {
// start of measuring
if (!$(this.parentNode).is('.' + ON_CLASS)) {
var re = /([_\-\w]+$)/i;
var target = $('#' + re.exec(this.href)[1]);
var startDate = new Date();
if (target.size() > 0) {
$(id + '>div:visible').hide();
target.show();
$(id + '>ul>li').removeClass(ON_CLASS);
$(this.parentNode).addClass(ON_CLASS);
} else {
alert("There is no such container.");
}
}
// end of measuring
return false;
});
};
Another little thing (because that was suggested once):
Brute force removing the 'on' class:
$(id + '>ul>li').removeClass('on');
wasn't measurably slower than picking the single element:
$(id + '>ul>.on').removeClass('on');
Regards
-- Klaus
_______________________________________________
jQuery mailing list
discuss@jquery.com
http://jquery.com/discuss/