You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何刷新页面时不丢失滚动位置?定时刷新脚本优化需求

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.scrollY works in most modern browsers, and document.documentElement.scrollTop is a fallback for older ones) and store it in sessionStorage—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.
  • sessionStorage is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:08:59