Boss lesson · Unit 03
Smooth rendering
One janky product list: layout thrash, shifts and long lists
What you practise
- Forced layout in a loop, what causes layout shift and how to reserve space, animating without layout, long lists
Try a question from this lesson
Pick one
A screen redraws 60 times a second. About how long does a page have to produce each frame before scrolling starts to stutter?
Hint
Divide one second by the number of frames in it.
Correct answer
About 17 ms
Why
1,000 ms / 60 frames is about 16.7 ms each. Scripts, style, layout and paint for a frame all have to fit in that, and the browser needs a little of it for itself. A frame that takes 40 ms means two missed redraws, which the eye sees as a jerk.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Forced synchronous layout
Normally scripts run, then the browser computes style and layout once, then paints.
If a script changes a style and then reads a size or position (offsetWidth, offsetTop, getBoundingClientRect()), the browser has to run layout on the spot to answer truthfully. Do that in a loop and you get one layout per item: layout thrashing.
The fix is an order, not a library: read everything first, then write everything.
thrash read write read write read write
one layout per item
batched read read read write write write
one layout per frameConcept
Long lists
Ten thousand rows are ten thousand elements to style, lay out and hold in memory, though fifteen fit on screen.
A virtualised list creates only the rows in view plus a small buffer, and replaces them as the user scrolls. A spacer keeps the scrollbar the right length.
A lighter tool is the CSS content-visibility: auto: the elements exist, but the browser skips their layout and paint while they are off screen.
row 0 not created
row 45 buffer
row 50 +--------------+
| viewport |
row 64 +--------------+
row 69 buffer
row 9999 not created10 more exercises in the app
- 3× type the answer
- 2× order the lines
- 1× fill the blanks
- 1× true or false
- 2× multiple choice
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.