Adds a customizable scroll-to-top button near the page bottom.
< Feedback on Scroll to Top Button
Thank you for the feedback! Yes, this actually aligns perfectly with why I modified the original script when you first shared it - the lazy loading issue was one of the key problems I noticed. Let me highlight this:
In the updated script (v2.1.0), I implemented several mechanisms to handle lazy-loading:
Added MutationObserver to watch for DOM changes:
const observer = new MutationObserver(debouncedScroll);
observer.observe(document.body, {
childList: true,
subtree: true
});
Improved scroll height calculations to account for dynamic content:
const scrollHeight = Math.max(
document.documentElement.scrollHeight,
document.body.scrollHeight
);
Enhanced the visibility logic to maintain button presence during content loading:
function shouldShowButton() {
const scrollHeight = Math.max(
document.documentElement.scrollHeight,
document.body.scrollHeight
);
const viewportHeight = window.innerHeight;
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
return (
scrollTop > CONFIG.showThreshold &&
scrollHeight > CONFIG.minimumPageHeight &&
scrollHeight > viewportHeight * 1.5
);
}
The original script had issues with lazy-loading because it only checked scroll position relative to the initial page height. The enhanced version actively monitors DOM changes and recalculates heights, ensuring the button remains visible and functional even as new content loads.
Firstly, nice script! Secondly, I noticed that if the page employed lazy-loading, the scroll-to-top button would disappear when scrolling further. I have made some modifications to mitigate this by watching for modifications to the DOM. Feel free to update your script.