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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With