3

I'd like to execute a javascript (or jQuery) initialization function -- let's call it myPageInit() after a page is fully loaded.

Here's the catch: myPageInit() should run only when the page is initially loaded or if the user forces a page refresh (i.e. presses the browser's reload button, hits F5, etc.). It should not run if the user follows a link from the page and then hits the back button.

For the avoidance of doubt:

  • User navigates to www.mypage.com => myPageInit() runs after page is loaded.
  • User now hits browser refresh button => myPageInit() runs after page is reloaded.
  • User now clicks on a link on the page (e.g. <a href="www.cnn.com">... ).
  • User clicks back button to get back to www.mypage.com => myPageInit() does not run after page is shown.

What I've tried so far

  • $(window).load() -- I think this used to work, but on modern browsers this appears to fire when the user presses the back button (see the comments on this issue)

  • $(window).ready() -- This also appears to fire on both initial load and back button.

  • Searching SO for other relevant answers. I still haven't found what I'm looking for.

Thanks in advance!

Community
  • 1
  • 1
tohster
  • 6,973
  • 5
  • 38
  • 55
  • Is [this question](http://stackoverflow.com/questions/6332844/javascript-detect-when-page-has-been-navigated-back-to) what you are looking for? – Joe Jun 21 '13 at 02:52
  • Thanks for the quick reply! Unfortunately it doesn't seem to address the problem. The accepted answer provides a hash tag change event library which doesn't address the initial page load trigger, and the comments to the OP point out behavior that I'm trying to get away from (ie onready fires on a back button). – tohster Jun 21 '13 at 16:16

1 Answers1

0

Maybe not exactly what you needed, but how about a session cookie or HTML storage flag? See code and answers at:

e.g. create session based cookie, jquery

Community
  • 1
  • 1
paulusm
  • 786
  • 6
  • 19