简体   繁体   中英

Sammy.js cache and scroll position when going back in history

I don't know if anyone is still using Sammy.js, but I found it perfectly suits my needs for a lightweight routing and templating library. If anyone has other ideas, please let me know.

My problem is that when I have a long page and I scroll down, click on a link on this page and go back, the whole page is reloaded (in Sammy, the GET route is called) and it jumps to the top of the page.

My question is: Is there a way to have Sammy cache the page and maintain the scroll position when going back in the history?

Thanks in advance.

You could use localStorage as alternative way to store url-scrolltop as a pair. This way the browser remembers srolltop position for the specified url.

var scroltop,url;
$(window).scroll(function() {
    scroltop = $(this).scrollTop();
    url = window.location.href;
    clearTimeout($.data(this, 'scrollTimer'));
    $.data(this, 'scrollTimer', setTimeout(function() {
    localStorage.setItem(url,scroltop);
    }, 250));
});
if(localStorage.getItem(window.location.href)) {
  url = window.location.href;
  scroltop = localStorage.getItem(url);
  $(window).scrollTop(scroltop);   
}

JSbin example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM