DEV Community

Discussion on: Quick and Easy JS Parallax Effect

Collapse
 
rikschennink profile image
Rik Schennink

Awesome!

Some performance improvements you could make. Don't adjust marginTop, it will cause a reflow (which means the browser has to recalculate all element positions), instead, update transform as that can be applied by the GPU, is hardware accelerated, and does not cause a reflow.

You can also request the scroll offset once and then loop over the elements. Requesting scroll offset will result in another reflow as the browser will have to calculate the offset to be sure it's returning the right value. Because you alter the marginTop the layout has changed and it will have to do this for each chip.

Marking the event listener as passive will result in another slight performance improvement, this tells the browser the event won't be cancelled.

The final thing todo is to only update the view when the browser draws to the screen. The prevents multiple calls to the function when only one of the calls is drawn.

Collapse
 
jon profile image
Jon Bishop

I missed that passive event listener adoption. So useful.

Collapse
 
gabe profile image
Gabe

This is awesome, and exactly the kind of feedback i was looking for when I originally posted this! Thank you! I’ll be giving your code a shot later today when I get into work.

Collapse
 
rikschennink profile image
Rik Schennink

Wonderful! Glad to hear it's of use to you!