Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I preserve dom state in the browser history after dynamic dom manipulation?

Is there a general purpose solution for preserving dom state so that when a user returns to a page by using back/forward, the whole page is in the exact state that they left it?

This post asks and answers why the behavior is inconsistent with different browsers and different javascript libraries...

Ajax, back button and DOM updates

...but I am curious if anyone has a general solution to this problem that doesn't require reloading the page.

like image 571
Pete Avatar asked Oct 15 '09 15:10

Pete


People also ask

Which method is used for DOM manipulation?

The jQuery after() method inserts content (new or existing DOM elements) after target element(s) which is specified by a selector. Syntax: $('selector expression').

How do I check stack history?

history object allows you to access the history stack of the browser. To navigate to a URL in the history, you use the back() , forward() , and go() methods. The history. length returns the number of URLs in the history stack.

Why real DOM manipulation is slow?

Answer. When there is a change to an element in the DOM, the DOM has to re-render the element and all of the element's children to the DOM - making DOM manipulation very slow in comparison to the Virtual DOM.


2 Answers

I'm afraid there isn't, and there really can't be because we're talking about browser behavior that's completely discretionary and not standards-defined. You could use Ajax to aggressively synchronize relevant DOM state to a session on a server, and always restore from that state on page load, but that will preserve the most recent state for that page, not the state that was necessarily present at a given desired point in the browser history.

like image 52
chaos Avatar answered Sep 21 '22 02:09

chaos


You can use this cache busting technique in rails to make it work in modern browsers (chrome, ie8+, ff 3.5+). This worked for me on my last project when we had ajax update the dom and had to navigate back and have the ajax updates persist.

response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
like image 26
trcarden Avatar answered Sep 19 '22 02:09

trcarden