I'm new to jquery, and only just realised that code in the .ready
function does not always get run when you return to a page using the browser's BACK button. From reading two-year-old posts on stackoverflow it appears that not all browsers work in the same way, and there is no single jquery function to solve matters. Is that still the case? What is the best method (in 2012!) for detecting whether a page is being run for the first time, or being shown again after the user has pressed BACK?
Just to be clear: imagine I had a page of red text where clicks changed words to blue with javascript/jquery......if I navigated to a new URL, then pressed BACK, the following would happen:
Firefox - words still blue
IE/Chrome - words gone back to red
Firefox
I understand Firefox and some other browsers implement the pageshow
and pagehide
events and do not fire the ready
event when showing a page from the 'bfcache'. Within this function you can check event.originalEvent.persisted
to see what the situation is.
IE/Chrome
I am aware of one trick that uses <input type="hidden" id="dirty">
to keep track of whether a page is loading for the first time in IE/Chrome. Not sure how reliable this is. I could also try a cookie I guess.
Apologies for complete ignorance...
Edit: Why do it?
My own situation would take ages to explain, but here's an inane example that has the same problem: Image a page that shows 10 playing cards, and the user can pick a card to make it move upwards on the screen. When you pick a card, an ajax request fires to send the card's details to the server. Now imagine you navigate away from the page, then use BACK to return to it. Three things can happen:
1. The browser may call the server to get the page, and the server (database) knows which card was chosen, so can output the relevant HTML/script
2. Firefox will use the bfcache to show your page - the chosen card will still be selected (moved upwards) as the state of the DOM was exactly preserved (the ready
event will not be hit)
3. IE/Chrome will reload the original HTML from the cache and call the ready
event's script.....showing all the playing cards in the 'unselected' position. Your chosen card is lost!