Execute document.ready even if user came to the page by hitting the back button

Viewed 18176

I have a PHP page with jQuery's $(document).ready() which does some changes to the form on the page. This works fine. But if I come to this page and then went to another and then hit 'Back' from the browser and came back to this page, the $(document).ready() function does not seem to run at all. This is happening on FF as well as Chrome.

Is there some way I can have document.ready executed even if the user hit the browser's back button to come to my page?

2 Answers

I had exactly the same problem; @Alfabravo's link helped me a lot here: https://stackoverflow.com/a/12648785/679240

The code below worked okay enough for me, since what I actually needed was to do some cleanup either when the user entered the page or when the page was reached through the back button:

$(window).on('pageshow', function(){
    console.info('Entered the page!');
});

If you need to specifically detect specifically when the page was reached through the back button but not when entering it the first time, you may need to control a bit of state; the link above may help you there.

Related