Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
166
rated 0 times [  173] [ 7]  / answers: 1 / hits: 5905  / 10 Years ago, wed, september 17, 2014, 12:00:00

I have an element I'm applying some basic transitions to based on scroll position. It works smoothly as expected in Safari and Firefox, but scrolling in Chrome is very choppy.



$(document).ready(function($) {
var divUp = $('.fade');
var divDown = $('.fade-down');
$(window).on('scroll', function() {
var st = $(this).scrollTop();
divUp.css({
'top' : -(st/6)+px,
'opacity' : 1 - st/400
});
divDown.css({
'opacity' : 1 - st/400
});
});
});


I commented out each CSS property individually, but Chrome is choppy either way. The top property is moving a relatively positioned element.



How can I achieve the desired effect while still making Chrome's JS engine happy? Thanks in advance for any feedback.


More From » jquery

 Answers
2

You're experiencing layout thrashing.



Changing an element's top property invalidates the current layout. Usually this prompts the browser to re-compute the layout asynchronously (i.e. not immediately).



However, calling scrollTop forces the browser to re-layout synchronously. Because you call it in a scroll event handler, this happens repeatedly in a very short space of time. This sequence of DOM write-reads is a known cause of jank.



To improve performance you need to prevent layout thrashing. Changing the CSS transform (and opacity) properties does not invalidate the browser's layout - they only require a composite, which is much faster.



If you animate a transform: translateY instead of top the browser won't need to compute costly calculations on every animation frame:



divUp.css({ 
'transform': 'translateY( ' + (-(st/6)) + 'px)',
'opacity': 1 - st/400
});


You can help the browser optimise for the transition by setting the CSS will-change property:



.your-div {
will-change: transform;
}


Further reading:




  • Jank free - Articles on improving web app performance

  • CSS Triggers - Lists the steps that browsers need to take when each CSS property is changed


[#42460] Tuesday, September 16, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ellisw

Total Points: 625
Total Questions: 92
Total Answers: 88

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
ellisw questions
Mon, Aug 23, 21, 00:00, 3 Years ago
Fri, Nov 20, 20, 00:00, 4 Years ago
Sat, Jun 20, 20, 00:00, 4 Years ago
Tue, Apr 21, 20, 00:00, 4 Years ago
;