Paul M
Paul M

Reputation: 366

Efficient use jquery scroll function

I want to check if the scrollTop is greater than 1. But when I use the following code, the scroll event keeps firing when the user scrolls which leads to bad performance.

$(window).on('scroll', function(){
        var scrollTop = $(this).scrollTop();

        if(scrollTop > 1){
            $('.header').addClass('active');
        }   else{
            $('.header').removeClass('active');
        }
    });

Is there a more efficient way to do this, so performance stays in check?

Upvotes: 0

Views: 80

Answers (1)

Tschallacka
Tschallacka

Reputation: 28742

For optimisations sake, stop requesting the header dynamically each time. Store a reference to the header in the window object.

$(document).ready(function() {
                          window.headerObject = $('.header');
                          window.jQueryWindow = $(window);
                          });
$(window).on('scroll', function(){
    var scrollTop = jQueryWindow.scrollTop();
    if(scrollTop > 1){
           window.headerObject.addClass('active');
    }   else{
        window.headerObject.removeClass('active');
    }
});

Instead of having to traverse the DOM to find .header multiple times each request and making a new jquery object of the window object each time, you simply store them, negating the initialisation cost improving speed.

if you want to comporare speeds:

$(document).ready(function() {
                          window.headerObject = $('.header');
                          window.jQueryWindow = $(window);
                          });
$(window).on('scroll', function(){
    starttime = performance.now();
    var scrollTop = jQueryWindow.scrollTop();
    if(scrollTop > 1){
           window.headerObject.addClass('active');
    }   else{
        window.headerObject.removeClass('active');
    }
    console.log('scroll optimised took' + (performance.now() - starttime) + " milliseconds");
});


$(window).on('scroll', function(){
    starttime = performance.now();
    var scrollTop = $(this).scrollTop();

    if(scrollTop > 1){
        $('.header').addClass('active');
    }   else{
        $('.header').removeClass('active');
    }
   console.log('scroll dynamic took' + (performance.now() - starttime) + " milliseconds");
});

scroll optimised took 0.060999998822808266 milliseconds

scroll dynamic took 0.26700000125856604 milliseconds

As you can see, the optimised code takes on average 0.06 milliseconds whilst the full dynamic selector takes 0.26 milliseconds. Quite the performance gain.

The delay might come more though from the calculations needed for restyling active than the cost of this loop.

Upvotes: 1

Related Questions