history.scrollRestoration Keeps Reload Position Stable

Choose manual or auto scroll restoration per route so long lists do not jump back to the top on reload or on back navigation.

JavascriptData Fetching

Code

javascriptsnippet
24 lines
// auto (default): the browser restores scroll on reload/back.
// manual: your code decides where the viewport lands.
const initial = history.scrollRestoration;
console.log('default mode:', initial);

// Long list views opt out of the jump-to-top behavior.
function openListView() {
  history.scrollRestoration = 'manual';
  console.log('list view:', history.scrollRestoration);
}

// Detail views hand control back to the browser.
function openDetailView() {
  history.scrollRestoration = 'auto';
  console.log('detail view:', history.scrollRestoration);
}

openListView();
openDetailView();

// The mode survives reloads as a browser behavior, not as page state —
// each route must set it again while booting.
history.scrollRestoration = initial;
console.log('restored:', history.scrollRestoration === initial);

How it works

The snippet is organized around the functions openListView and openDetailView.

Watch out for

  • The whole dependency story is the language version itself.

Using it

Signature: function openListView()

The demo output is labeled (default mode:, list view:, detail view:), so every printed line maps back to its originating operation.

Key statements

const initial = history.scrollRestoration;
history.scrollRestoration = 'manual';
history.scrollRestoration = initial;

Interactive Tools for This Topic

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches. The file defines `openListView`, `openDetailView` at load time.