A classic case of potential layout thrashing!
What is layout thrashing?
Layout thrashing occurs when your code repeatedly reads and writes to the DOM (or layout-dependent properties) in a way that forces the browser to recalculate the layout multiple times, leading to performance issues, jank, and a poor user experience.
Where is the problem in your code?
The main culprit is the checkBottom() function, which is called:
- Directly after
scrollToTop() and scrollToAnchor()
- On every
scroll event (via the document.addEventListener("scroll", ...) callback)
- Inside the
MutationObserver callback (indirectly, via scrollToBottom())
checkBottom() reads several layout-dependent properties:
document.documentElement.scrollHeight
document.documentElement.offsetHeight
window.innerHeight
window.scrollY
and then writes to the DOM:
The issue arises because reading layout-dependent properties can trigger a layout recalculation if the browser's cached layout is invalid (e.g., after a scroll or mutation). If you then write to the DOM, the browser needs to recalculate the layout again. Repeat this process multiple times in a row, and you get layout thrashing.
How to avoid layout thrashing here?
- Batch reads and writes: Group all your reads together, followed by all your writes. This minimizes the number of layout recalculations.
- Use
requestAnimationFrame (rAF): Debounce your writes to the next animation frame, ensuring they happen after the browser has a chance to update the layout.
- Cache values: Store layout-dependent values in variables and reuse them instead of re-reading them multiple times.
Here's the refactored checkBottom() function: