When you go back to a page already visited the browser scrolls the page to the point you were when you left the last time.
A scrollTo
invoked at window.onload
either is ignored or it is executed before the browser gets into the way and restores the scroll position.
This is intended to give the user a better browsing experience, actually this is what normally a user expects, expecially when navigating back to the page via the "back" button.
But, if you really want to, you can override the browser behaviour by letting some time pass after onload
and before your code scrolls the page to (0,0)
:
window.onload = function () {
setTimeout( function () {
window.scrollTo(0, 0);
}, 500 );
};
This way window.scrollTo
is "scheduled" to be executed 0.5 seconds after page is loaded.
...and will succeed.
See also Prevent automatic browser scroll on refresh
Note: since window.onload
fires when the entire page has loaded (included images, links, frames...) the event (and subsequent scroll to (0,0
) may be excessively delayed or not fired at all (if a resource fails loading).
I suggest to use (or at least try) document.onload
that fires when the page has been parsed, the DOM structure is ready and linked resources start loading.
Your code becomes:
document.onload = function () {
setTimeout( function () {
window.scrollTo(0, 0);
}, 500 );
};
Since this triggers very early if you have issues you may raise a little the delay value to 750
or 1000
milliseconds.
For your reference you may find useful: window.onload vs document.onload