Using PageShow To Detect Cached Pages

Recent upgrades in browsers and features has left the page “load” event not reacting like you’d expect anymore. Normally by setting certain metatags in the page and sending cache breaking http headers, you could get the web page to reload with each page view and use the “load” event to initialize the page. Unfortunately this is not the case anymore. While testing with iPhone Safari, I discovered that no meta tags or headers would stop it from caching my javascript application. So whenever I hit the back button back to my app page, the js app would not initialize properly. After reading about the pageshow event I found that I could detect when the user had come back to a cached version of the page by checking the “persisted” property in the pageshow event in jQuery like so…

$(window).bind( 'pageshow', function( event ){
   if( event.persisted ) {
      window.location.reload();
   }
});

This code will force a page refresh when the javascript detects that this page has been loaded from cache. Although future javascript web page apps should be more elegantly coded to work with page caching, this is a quick fix for pages that I don’t have time to rebuild from scratch.