Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why will changing this CSS effect using JS only work smoothly for certain values?

I am trying to move an image slowly relative to the viewport when the user scrolls the page. Similar to the effects found here https://ihatetomatoes.net/demos/parallax-scroll-effect-part-2/

If the image is moved by a small value then it moves smoothly. If it is moved by a larger amount then it becomes very janky.

var imageOffset = lastScrollY * 0.9;
$image.css({top: `${imageOffset}px`});     //Runs badly

var imageOffset = lastScrollY * 0.3;
$image.css({top: `${imageOffset}px`});     //Runs well

Why does the value affect the performance so much?

I have tried all the different CSS styles (transform, top, bottom, background-position). Dev tools says that I am well in the time limit for 60fps. This happens if there is nothing but the image on the page and on multiple browsers and devices. This is also not just for images but for text or anything else as well.

Bad Version: https://jsfiddle.net/4vcg8mpk/58/

Good Version: https://jsfiddle.net/4vcg8mpk/59/

Problem most noticeable in Firefox, in Chrome it is noticeable on first scroll and then settles down. Also most noticeable using scroll wheel or trackpad instead of dragging side scroll bar

like image 671
Tristan Warren Avatar asked Dec 11 '22 05:12

Tristan Warren


1 Answers

This is because you are trying to animate properties that impact page layout. These properties require the browser to recalculate layout of the DOM each time a layout property changes. You may not be experiencing performance lag in the second option because the layout repainted quickly, but that doesn't mean you are not going to eventually encounter performance issues while animating those properties.

I'd recommend checking out this article on animation performance with CSS. It is old, but the information is still valid. I know you say that you tried animating other properties, but I would recommend taking a look through all of those recommendations and then implementing something that is going to be "cheap" for the browser.

like image 60
brianespinosa Avatar answered Feb 09 '23 01:02

brianespinosa