Keep changes on DOM when pressing back/forward but

2019-10-07 10:17发布

I have already seen similar questions like: Ajax, back button and DOM updates, and in fact, what I tried so far is inspired by the answers on those. However, none of them describe the problem I'm facing when actually applying their suggestions

This is what is happening right now:

  • Page A performs an ajax call which I will use to update elements on the DOM 'chosen quantity for example'
  • User goes to Page B and does the same
  • User clicks the back button
  • Page A loads but all the changes I did on the DOM are lost
  • User clicks the forward button
  • Page B shows and all the changes are lost as well

What I tried so far: - Reload the quantities on jQuery's ready method. This works... although the user can see for a few seconds the old quantities. However, it has a big downside because it duplicates the amounts of calls sent to the server

  • Update the window.location.hash value after each ajax call. I.E

    window.location.hash = new Date().getTime();

This also works, but the problem is that I have to click the back button twice instead because the first click reloads the current page.

Any ideas how to fix this? What I want to do in the ends is conserve the DOM state in order to avoid extra calls to server in order to update my quantities.

Thanks

1条回答
霸刀☆藐视天下
2楼-- · 2019-10-07 11:04

If you're really changing pages, the yes, even if working from cache the browser will show the page as it was when retrieved from the server, not as it was when modified afterward.

If you want to keep the Page A / Page B structure the way it currently is rather than swapping over to a more SPA approach, you could store the ajax result in sessionStorage and check for it on page load. If there, reapply it; if not, request via ajax and apply it (and save it). That will be much faster than re-requesting it across the network.

查看更多
登录 后发表回答