Jump to content
Search Community

Idea - Calling ScrollTrigger.refresh() at a set interval on a complex site with several timelines and scroll triggers

Flying Fish test
Moderator Tag

Recommended Posts

I've been exploring a solution to keep ScrollTriggers working smoothly. In my case there are several timelines, ScrollTriggers, and svelte components that are modifying the DOM at different places on a long page. To help with this I created a function that calls ScrollTrigger.refresh()every couple of seconds, and it does not refresh if the user is scrolling. So far it's been working pretty well, but I wanted to post the solution here to get input on pros and cons.

 

The JS looks like this, where the imported refreshScrollTriggers function is a debounced call to ScrollTrigger.refresh():

 

import { refreshScrollTriggers } from './events'

/**
 * Refreshes GSAP scroll triggers at a specified interval, when the user is not scrolling.
 *
 * @return {void}
 */
export default () => {

    const interval = 2400
    const waitAfterScroll = 400

    let isScrolling = false
    let timer = null

    const handleScroll = () => {
        isScrolling = true
        requestAnimationFrame(() => {
            clearTimeout(timer)
            timer = setTimeout(() => {
                isScrolling = false
            }, waitAfterScroll)
        })
    }

    window.addEventListener('scroll', handleScroll)

    setInterval(() => {
        if (!isScrolling) {
            refreshScrollTriggers()
        }
    }, interval)
}

Feedback welcome.

Link to comment
Share on other sites

Hi,

 

If is doing what you want and not creating any issues, then is working properly.

 

Although it seems redundant to call refresh when the DOM is not updated. I assume that there could be some point when the DOM is not being updated and the user is not scrolling, so at that point running all the logic ScrollTrigger runs on the refresh method is completely unnecessary and wasteful IMHO. Also another scenario could be that the DOM is updated while the interval is actually running and just one second has elapsed, the user would have to wait another 1.4 seconds for the refresh method to be executed and all the calculations, start and end points to be updated. Why not create a global method that can be called whenever one of this components actually updates the DOM? That would be my approach, assuming you have control over this components in some way, or access to some type of callback after the DOM is updated. That makes more sense to me actually.

 

Hopefully this helps.

Happy Tweening!

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...