如何刷新页面时不丢失滚动位置?定时刷新脚本优化需求
Preserve Scroll Position on Auto-Refresh
Hey there! The problem with your current script is that location.reload(false) doesn't keep your scroll position when the page refreshes—you end up back at the top every time. Let's fix that by saving your scroll spot before reloading and restoring it afterward.
Here's the updated script that does exactly that:
// Restore scroll position when the page finishes loading window.addEventListener('load', function() { const savedScrollPos = sessionStorage.getItem('scrollPosition'); if (savedScrollPos) { window.scrollTo(0, parseInt(savedScrollPos)); // Clear the saved position so it doesn't mess with manual navigation later sessionStorage.removeItem('scrollPosition'); } }); // Set up 10-second auto-refresh interval const idleInterval = setInterval(reloadPage, 10000); function reloadPage() { // Save current scroll position before reloading const scrollPos = window.scrollY || document.documentElement.scrollTop; sessionStorage.setItem('scrollPosition', scrollPos); // Reload the page (using false to load from cache, same as your original) location.reload(false); }
How this works:
- Saving the position: Before the page reloads, we grab the current vertical scroll position (
window.scrollYworks in most modern browsers, anddocument.documentElement.scrollTopis a fallback for older ones) and store it insessionStorage—this is a browser storage that keeps data only for the current tab, so it won't affect other pages or sessions. - Restoring the position: When the page finishes loading again, we check if there's a saved scroll position. If there is, we scroll the window to that position and then clear the saved value so it doesn't force you back to that spot if you navigate away and come back later.
Quick notes:
- This works best if the page content doesn't change drastically in height between refreshes—if new content adds a lot of space above your scroll position, the restored spot might be slightly off, but it's still way better than jumping to the top.
sessionStorageis supported in all modern browsers, but if someone has it disabled for some reason, this method won't work—though that's a rare case.
内容的提问来源于stack exchange,提问作者Shrikant Kumbhar
相关产品推荐
相关产品推荐

