Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Parallax / Scroll Events Performance

This question pertains less to parallax than it does to scroll events. My overriding concern with my project is that the parallax scroll effect is smooth and not jittery.

My question then is, do certain properties animate / scroll better than others? For example does background-position work better than say adjusting margin-top on scroll.

like image 438
Philip McLaughlin Avatar asked Jan 18 '12 18:01

Philip McLaughlin


1 Answers

I'm not sure if some properties create less overhead while animating than others but I would be very interested if someone posts some good information on that subject. That being said I do know of a couple things that can help performance.

Setting position : absolute removes the element from the regular flow of the page and therefore does not require the entire page to be redrawn when it is animated. position : relative will force a redraw of the whole page since ancestor and descendant elements can be affected.

Also, you can throttle the scroll event and still achieve 30fps:

var scroll_ok = true;
setInterval(function () {
    scroll_ok = true;
}, 33);//33ms is 30fps, you can try changing this to something larger for better performance
$(window).bind('scroll', function () {
    if (scroll_ok === true) {
        scroll_ok = false;
        //now run your code to animate with respect to scroll
    }
});

UPDATE :: 2014-08-26

Things have changed since this was originally written. A few quick notes:

  • Modern browsers now attempt to GPU accelerate the painting of elements given a specific set of properties (opacity and transform off the top of my head). Using these properties can greatly improve performance over others like top/left (which also require redrawing the page in more instances than using a transform).

  • will-change is a new property just being picked up by browsers. You can basically set a list of properties that are likely to change so the browser can optimize the property change ahead of time.

  • requestAnimationFrame has a robust polyfill and good modern browser support. This is a much better way to smoothly animate elements without creating tons of "chunk" as the browser will render as it can.

like image 170
Jasper Avatar answered Oct 22 '22 21:10

Jasper