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

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);
}

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.