Preserve dynamically changed HTML on back button

Madd0g picture Madd0g · May 8, 2013 · Viewed 32.8k times · Source

It's amazing, I constantly see this working in other sites but never in sites that I'm working on.

I'm bringing in new content with ajax, I know about history.js and the History API, I do not want to change the URL, just have the browser cache the new HTML content so when a user leaves the page and comes back using the back button, it still has the updated HTML.

I see this working all the time in other sites without URL changes or using the hash #.
Is there a trick to get it to work or is it randomly decided by the browser?
If I don't want to use the URL to have this information, is there an easy alternative?

Answer

Groover picture Groover · Jun 9, 2013

For about a decade and half now, I have been using two tricks that I once discovered by painful trial and error: Input field values - especially 'hidden' ones - are preserved in the browser's history along with the URL - AND - the onLoad event is called when returning to the page by the back (or forward) buttons.

This means that you can store as much 'state' as you like - in hidden fields (remember to put them in a form), and then 'redo' the changes on 'onLoad'. I usually make the 'render' part a separate function... In other words, at the time that the dynamicness is occurring, I first write to the hidden fields - then call the render function. Then I gather together all the various render functions for the various bits of dynamicness and call them from the onLoad.

I would stress that I have never gone hunting for this in any manuals - so cannot offer any assurances - but I have been using it reliably for a good while (since Netscape!!!) It works with 'many' browsers (all the IEs, chrome, FF - but as for the others, I've never tried.)

If anyone has a more 'correct' - and less tedious - way, I for one, will be very glad to hear about it. But this does seem to do the trick.