How to save/cache the dom so that the page loads as-is when you hit the back button?

285 Views Asked by At

i add models to my js app model collection using ajax calls. when i click a model and go to the next page, i want all the models i had loaded to still be there when i hit the back button. what is the best way to do this so that it works on all browsers? this is for mobile web. i can't find a straight answer, how do i use bfcache, or js history, or is there another, better way?

1

There are 1 best solutions below

11
O_Z On

You can store them in the local Storage and ajax for them only if the do not exist on the local Storage

So instead of using the regular $.ajax , use this for the ajax that you want cached:

function storageBasedAjax(url,cb){

    if (localStorage.getItem("myAxaxCache_"+url)){
      cb(localStorage.getItem("myAxaxCache_"+url));
      return;
    }       

   $.ajax({url: url, success: function(result){
     localStorage.setItem("myAxaxCache_"+url,result);
        cb(result);
   }});
}

Just remember you do not want to over load, so if you have a url with a parameter changing each call,do not use this or you will overload the local storage