Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
60FPS onscroll event listener
(function() {
var lastScrollY = 0;
var ticking = false;
var update = function() {
// do your stuff
ticking = false;
};
var requestTick = function() {
if (!ticking) {
window.requestAnimationFrame(update);
ticking = true;
}
};
var onScroll = function() {
lastScrollY = window.scrollY;
requestTick();
};
$(window).on('scroll', onScroll);
})();
@paulmillr

This comment has been minimized.

Copy link
Owner Author

paulmillr commented Jul 15, 2012

This requires requestAnimFrame polyfill.

It allows to simply make "fixed-static" sidebars etc.

// In do your stuff section
if (lastScrollY > 230) {
  nav.css({position: 'fixed'});
} else {
  nav.css({position: 'absolute'});
}
@saxinte

This comment has been minimized.

Copy link

saxinte commented Dec 23, 2015

Do you have an idea why this is more performant than using a throttle on scroll event? What rAF improve in this context? Because if you console.log('test') in the update function and in the onScroll function, it's firing exactly the same number of logs.

@kurtextrem

This comment has been minimized.

Copy link

kurtextrem commented Dec 28, 2015

@saxinte: console.log is not an expensive function. But most of the time scroll listeners do very expensive work, such as querying dom elements, reading height / width and so on.

@saxinte

This comment has been minimized.

Copy link

saxinte commented Jan 4, 2016

@kurtextrem Yes and I've tested it. I see no difference with or without rAF. I created a simple Gist here: https://gist.github.com/saxinte/6bfdebdb8941bd5dd155
Try to call 'onScroll' function first and then 'update' function directly (on the scroll event) to avoid rAF. I have no perf difference in the timeline and both function are invoked the same number of time.

@roborourke

This comment has been minimized.

Copy link

roborourke commented Apr 20, 2017

@saxinte what were you testing on? A good enough laptop or desktop probably wouldn't struggle but mobile & sites with more complex layouts to calculate and repaint would probably start to show differences.

@htulipe

This comment has been minimized.

Copy link

htulipe commented Jun 26, 2017

window.scrollY force a reflow according to Paul Irish's Gist and is executed outside of a requestAnimationFrame in your sample code. Isn't that a problem ?

@alvarotrigo

This comment has been minimized.

Copy link

alvarotrigo commented Dec 2, 2017

Why the scroll event at all? Why not use use only requestAnimationFrame as suggested here?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.