I'm having a little problem with Safari - When i want to update a DOM element's position on scroll event, Safari seems not to catch up with the changes (resulting in a jumpy lag effect). I checked it on other browsers (Chrome, FF, IE8+) and this seems to be specific to Safari.
I made a jsfiddle to illustrate my problem:
$("#container").on("scroll", function() {
$("#slide").css({
left: $("#container").scrollLeft() + "px"
});
var leftPos = 0;
for(var i = 0; i < 2000 ; i++) {
leftPos = $("#slide").css("left");
}
$("#info").text(leftPos);
});
http://jsfiddle.net/a4b86et3/2/
As you can see, I added an additional loop of DOM reading on each scroll to simulate "more operations going on" on each event occurrence, as this mechanism is a part of a bigger project, which contains many other DOM operations. (Notice, that this example works smooth everywhere except Safari)
Also, i used jQuery just for the convenience, the actual project uses pure js.
I managed to partially fixed the issue
by changing the left = x
property to transform = translate3d(x,0,0)
, so the browser would use the GPU.
$("#container").on("scroll", function() {
$("#slide").css({
'-webkit-transform': 'translate3d(' + $("#container").scrollLeft() + 'px, 0, 0)'
});
var leftPos = 0;
for(var i = 0; i < 1900 ; i++) {
leftPos = $("#slide").css("left");
}
$("#info").text(leftPos);
});
http://jsfiddle.net/a4b86et3/3/
However, sometimes I'm still experiencing a slight lag/glitching while scrolling.
But, what's more important, this fix doesn't affect the scrolling, when I'm using a mouse scroll or touchpad! While dragging the scrollbar works way better, using any of the above brings me back to my initial problem.
Any ideas why this happens and how to fix it?
tl;dr; - Safari is slow when changing element position on scroll; translate3d seems to not work properly when using mouse scroll/touchpad.