Pablo
Pablo

Reputation: 3467

Browser cache issues when loading content through AJAX

I'm having some issues when rendering a website that I can only attribute to the browser caching an old version of my page.

Here's what's happening, my website shows a cart at the right side of the screen that's updated every time the user hits the buy button next to each item.

Let's say my cart is empty, the user hits buy over an item and the bar updates itself to reflect the newly added item... keep in mind that I'm achieving this through the usage of an Ajax call (jQuery), so far everything works perfectly.

However, if I hit the browser's back button and quickly press forward to return to page Chrome will render the version that was loaded before the AJAX calls. Here are a few things I noticed while debugging the problem.

  1. This only happens in Chrome and Firefox
  2. The cart is not emptied if I refresh the page
  3. In Chrome, if I try the steps mentioned above while having the developer tools tab open (Cache disabled) the bug is not occurring
  4. In Chrome and without the developer tools, if I hit the back button and wait for at least 60 seconds and the return to the page, the problem doesn't show
  5. In a similar way, if I wait for at least 60 seconds after adding the item to the cart, go back and forward, no issue can be seen

Any ideas on what can I try to avoid this? Preferably javascript or tags since I have no control over the HTTP code that setups the headers.

I'm aware of the following code in order to force or "suggest" a cache flush. However, it only works with HTML5

// Check if a new cache is available on page load.
window.addEventListener('load', function(e) {

  window.applicationCache.addEventListener('updateready', function(e) {
    if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
      // Browser downloaded a new app cache.
      // Swap it in and reload the page to get the new hotness.
      window.applicationCache.swapCache();
      if (confirm('A new version of this site is available. Load it?')) {
        window.location.reload();
      }
    } else {
      // Manifest didn't changed. Nothing new to server.
    }
  }, false);

}, false);

Upvotes: 0

Views: 458

Answers (1)

kevin628
kevin628

Reputation: 3526

Try appending a random query string to the url you're hitting with AJAX.

var url = 'http://some.url.com/thing?' + new Date().getTime();
$.get(url);

This works so long as there aren't multiple requests happening in the same millisecond.

Upvotes: 1

Related Questions