Search code examples
javascriptjqueryhtmlcssparallax

Web page with parallax lags on scroll


I'm currently developing a web page with a scrolling parallax effect (Stellar.js) on the header and three other sections of the site: however, scrolling them causes lag, especially at the top of the page.

I've already tried to reduce the background images' size by using compression, but it hasn't made too much difference; removing the blur effect didn't solve the problem, either (it did reduce the lag, but it still wasn't smooth enough).

The website runs pretty well on Firefox (W10), with almost no frame drops, but there's quite some lag on Chrome (both Windows and OS X) and Safari.

There's a few JS scroll-triggered scripts running, but I don't know if those may be the cause. Any suggestions?


Solution

  • What you're going to want to do is throttle scroll events. Debouncing events means an event can't fire again until after a certain amount of time. Throttling events means that the event can only fire so much per period of time.

    Here's function to throttle events (credit: http://sampsonblog.com/749/simple-throttle-function)

    // Create the listener function
    function throttle (callback, limit) {
        var wait = false;                 // Initially, we're not waiting
        return function () {              // We return a throttled function
            if (!wait) {                  // If we're not waiting
                callback.call();          // Execute users function
                wait = true;              // Prevent future invocations
                setTimeout(function () {  // After a period of time
                    wait = false;         // And allow future invocations
                }, limit);
            }
        }
     }
    

    To use it just do something like this:

    function callback () {
        console.count("Throttled");
    }
    
    window.addEventListener("scroll", throttle( callback, 200 ));