Since Google Chrome for mobile does not store DOM status* of pages they left, you need to write logic to preserve and restore it if you'd like to offer same experience with for existing browsers, like the default browser for Android or PC browsers.
* When you visit Wikipedia from mobile Google Chrome and expand sub categories, then go to another page and return back, you can see that the category you expanded is folded.
Below is an alternate solutions to preserve DOM status with hash fragments.
Supposed:
| First Load | Browser Back | ||
|---|---|---|---|
| window.onload | Mobile Chrome | Fires | Fires |
| Other browsers | Fires | Not | |
| window.pageshow | Mobile Chrome | Fires | Fires |
| Other browsers | Fires | Fires | |
| evt.persisted (of window.pageshow) | Mobile Chrome | false | false |
| Other browsers | false | true | |
Thus:
$(document).ready(function() {
// Browsers which do not preserve DOM status like
// Google Chrome for mobile, whenever they load pages
// fire onload event no matter if it is from the browser
// back.
// Thus we regard onload event with the hash frag 'stat='
// as a browser back from histories.
if (window.location.hash.indexOf('#stat=') > -1) {
var arrStat =
window.location.hash.substr('#stat='.length).split(',');
// The reconstruction processes goes here
window.scrollTo(0, arrStat[0]);
// clears the unnecessary history for users.
history.back();
} else {
// some default init procedure goes here
}
});
window.addEventListener('pageshow', function(evt){
if (evt.persisted === true &&
window.location.hash.indexOf('#stat=') > -1) {
// For the browsers preserving DOM status,
// clears the unnecessary history.
history.back();
}
});
/**
A transition logic you need to append to click events of
elements like anchor tag.
( In practice, you can detect if the browser will preserve
DOM status in 'pagehide' event callback.
However, if you manipulate the hash fragment in
'pagehide' callback, browsers will fall in an infinite
loop so it is necessary to append a hash fragment
for transitions of all browsers)
*/
transitTo = function(evt) {
// Serializes DOM status and add them into the browser history
window.location = '#stat=' +
[document.body.scrollTop,
window.location.hash.substr(1)].join(',');
return true;
}
Note
A drawback:Unexpected history in the go-next stack would be left for users. You need to customize it if needed.
q.v.
Safari - Blog Archive » WebKit Page Cache II - The unload Event
https://www.webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/
No comments:
Post a Comment