How to make faster scroll effects?
- Avoid too many reflows (the browser to recalculate everything)
- Use advanced CSS3 for graphic card rendering
- Precalculate sizes and positions
Beware of reflows
The reflow appens as many times as there are frames per seconds. It recalculate all positions that change in order to diplay them. Basically, when you scroll you execute a function where you move things between two reflows. But there are functions that triggers reflows such as jQuery offset, scroll... So there are two things to take care about when you dynamically change objects in javascript to avoid too many reflows:
- use window.pageYOffset to get the scroll position
- prefer requestAnimationFrame than onScroll event.
Why is requestAnimationFrame (really) faster than the scroll event? Actually the scroll event popups whenever it wants, even if you haven't finished calculating the previous position, or between two reflows... While the requestAnimationFrame can only popup if the previous frame was calculated. So you save reflows out of your loop function, and you manage to never overlap two calculations.
// Detect request animation frame
var scroll = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
// IE Fallback, you can even fallback to onscroll
function(callback){ window.setTimeout(callback, 1000/60) };
function loop(){
var top = window.pageYOffset;
// Where the magic goes
// ...
// Recall the loop
scroll( loop )
}
// Call the loop for the first time
loop();