How to Force Scroll to the Top of the Page on Page Reload Using JavaScript?

Ensure that the browser scrolls to the top of the page when the page is refreshed

Browsers tend to restore the last scroll position on page reload. The precise moment at which they do that is hard to determine, and it may vary from browser to browser. Therefore, simply scrolling back to top on "DOM ready" or page load event might not guarantee it. This is why, in this article, we will show you ways in which you can ensure that the browser always scrolls to the top when the page refreshes.

Using history.scrollRestoration

The JavaScript history API has the scrollRestoration property, which when set to manual, prevents the last scroll location on the page to be restored. You can use it in the following way:

history.scrollRestoration = 'manual';

For browsers that don't support this, you could create a fallback to using window.onbeforeunload, for example, in the following way:

if (history.scrollRestoration) {
    history.scrollRestoration = 'manual';
} else {
    window.onbeforeunload = function () {
        window.scrollTo(0, 0);
    }
}

Using window.onbeforeunload

Before the page unloads, we can change the scroll position to the top of the page. This would change the browser's last scroll position, and when the page refreshes it would start at the top of the page. For example:

window.onbeforeunload = function () {
    window.scrollTo(0, 0);
}

Hope you found this post useful. It was published . Please show your love and support by sharing this post.