Search code examples
javascriptjquerywebkitscrolllag

jQuery’s css() lags when applied on scroll event


I’m trying to implement a simple “fixed headers” table. I know this can in theory be done with CSS only, but it doesn’t work very well when it comes to OSX Lion and its disappearing scrollbars. So I’m doing it with jQuery.

An approach is simple, it’s just 1.5 lines of code:

$('.inbox').scroll(function() {

    $(this).find('.inbox-headers').css('top', $(this).scrollTop());

});

Demo.

This works fine and smooth in Firefox, but lags horribly in webkit browsers. Why is that happening and how do I optimise this code? Or maybe approach the problem differently.


Solution

  • The "scroll" event is fired very frequently. It's always going to be really hard to keep up if you're modifying the DOM while scrolling in some browsers.

    What you can do is one of these things:

    1. In your case, position: fixed; might be a good alternative.
    2. If not, then have the event handler start a timer for like 100 milliseconds in the future, canceling any previous timer in the process. That way, the DOM will be updated only after scrolling stops or pauses.
    3. If you want continuous updates, keep track of the timestamp when you do an update, and do nothing in the handler if it's been less than some amount of time (100ms or whatever).