Jorge glez
Jorge glez

Reputation: 11

Quick and easy jQuery scroll question

I'm developing a website that adds certain classes to body when the user reaches certain parts in the page, etc. As a result, I have to bind a function to the scroll event.

Is it better to cache the scrollTop() like this (short example, the actual function is longer):

scrollcheck: function() {

    var top = main.documentquery.scrollTop();

    if(top > 60) {stuff}
    if(top > 220) {more stuff}

Or just use main.documentquery.scrollTop() in all instances?

(documentquery is $(document), I remember caching that being good, but I'm not sure about scrollTop())

Upvotes: 1

Views: 258

Answers (2)

Gijs
Gijs

Reputation: 5262

Yes, it's better to cache it, but it's also better to throttle the calls to this function. That will probably make a bigger performance impact. In particular, I would use a timeout pattern along these lines:

(function() {
    var _timeout = null;
    function onScrollHandler() {
        if (_timeout) {
            clearTimeout(_timeout);
        }
        _timeout = setTimeout(function() {
            _timeout = null;
            realScrollcheck();
        }, 500);
    }
    $(window).scroll(onScrollHandler);
 })();

There'll be a half-second delay after the last scroll for your function (called realScrollcheck here) to run, but in 99% of cases that's acceptable. Adjust the timeout at your leisure. :-)

Upvotes: 1

natedavisolds
natedavisolds

Reputation: 4295

Yes. It is better to store the value instead of calling it each time.

Upvotes: 0

Related Questions