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.