I am trying to avoid reloading as much as possible when browsing back and forth in my mobile webapp. JQuery Mobile seems to be designed for that but I am having troubles taming this behavior.
Basically, I have two pages (page1 and page2). page1 has a link to page2 and vice versa. The first time they are loaded, both pages (i) load data in ajax and (ii) change the DOM structure accordingly. I use a global var to avoid reloading the data, which works quite well.
Let’s say page1 (resp page2) has a DOM structure called dom10 (resp dom20) in the html and dom11 (resp dom21) after everything is loaded.
Here is my problem:
-
I load
page1, the data is loaded and the DOM is changed fromdom10todom11 -
I then click on
<a href="page2">click</a>,page2is loaded, the data is retrieved and the DOM is changed fromdom20todom21. So far so good. -
I then click on
<a href="page1">click</a>to go back. The page is just as I left it withdom11. Wonderful, there were noGETcall at all. -
I finally click on
<a href="page2">click</a>again and that’s where it hurts. The page is loaded again (GETcall), the data is not retrieved but the dom is set back todom20
I can keep on clicking back on forth and I always get the same behavior. Whenever I click on page1 I get the DOM just as I left it, whenever I click on page2 there is a GET call and the DOM is reloaded.
So here is my question, is there a way to prevent reloading a page that was already loaded in jQuery Mobile?
I can think of workarounds to have my DOM as I want but I would love to avoid unnecessary calls slowing down my app.
If you want to play around with it, you can try it there.
Thanks a lot for your help!
PS: Surprisingly, I don’t get the same behavior on Firefox and Chrome… I am afraid it is not so simple.
By default jQM always makes an AJAX request for pages even if you’ve already visited it before. If you set
$.mobile.page.prototype.options.domCache = true;then only will jQM not reload pages.If so you will need to set
reloadPageto true when you call $.mobile.changePage if you need to refresh the page – otherwise the page will be stale.Becareful though, if you do this all your pages will be appended to the DOM resulting in a massive DOM which impacts performance – you’ll need to manage it all properly in your JS which is a different topic. But imagine doing an open-ended $(‘.myClass’) search when you have 20 pages in your DOM. I have more details in an older answer I wrote: Jquerymobile – $.mobile.changepage