ScrollX, Scroll Why? History!

Discussion of the scroll history persistence problem, and proposal for solution.

In this blog, I propose a solution to a problem facing developers in the single-page application space, especially the mobile subspace.

The challenge revolves around a pesky behavior present in all popular browser implementations. This is the automatic restoration of last scroll position upon return to each page in a browser session. If and when the user returns to a page already visisted in a session, the browser automatically triggers an uncancellable scroll event to forcibly restore that scroll position after its DOM has loaded. Likely first envisaged as a convenience, this feature has become a thorn in the side of single-page application development.

Many single-page web applications have the need to hook into browser history and support deep-linking. Traditionally, this is accomplished via the use of fragment identifiers (a.k.a. URL hash) and the “hashchange” event. Because of the shortcomings and hackiness of that traditional approach, a new specification began to emerge called the HTML5 History API. It gives single-page applications the ability to manage and manipulate browser history via JavaScript. Its browser support is still mediocre.

But a major shortcoming remains. The new API provides no means of preventing or overriding the automatic restoration of scroll position.

This limitation has resulted in even some of the most popular mobile web application frameworks, notably jQuery Mobile, resorting to ridiculous hacks to manage scroll position between pages.

I propose a new standard that disables this behavior on a opt-out basis. In this way, it is completely backwards-compatible.

<meta name="scroll-history" content="false" />

And a new property in JavaScript to access the persisted scroll position, if desired:

window.history.scrollX; // e.g. 0
window.history.scrollY; // e.g. 432

What do you think? I think: W3C, get on it!