Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

javascript - Keep changes on DOM when pressing back/forward buttons

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...