How can I delay page transition in jQuery Mobile until page data is ready?

I had this exact same problem.

The only solution I've been able to come up with is to write a custom transition handler that defers starting the transition until the Ajax request completes.

Here's a fiddle showing the technique. The fiddle doesn't use Knockout, but does show how to defer the transition.

Basically, since $.ajax() returns a promise, I can pipe that into the promise returned by the default transition handler and return it from my new handler.

In my pagebeforeshow handler, I attach the Ajax promise to the page so that the transition handler has access to it. Not sure if this is the best way, but I liked it better than using a global variable.

The only thing I didn't like about this is that it delays the start of the transition until the Ajax response arrives so it could feel like the page has "hung" to the user making them click again. Manually showing the loading message makes it feel a bit more responsive.

Hope this helps and please let me know if you find a better solution!


Delaying the transition to a new page until its content is ready is a very common issue when facing dynamic content in jQuery Mobile. The most convenient ways to address this are:

  • Instead of classic href type navigation, base the links on "click" actions that will first retrieve the content, build a new page in the DOM, and then initiate a transition to this new page through $.mobile.changePage. The advantage of this approach is that it is easy to put in place, the disadvantage is that you do not navigate with classic href links

  • Bind the pagebeforechange event at the document level to detect if upon navigation the target page is one of your page that should contain dynamic content. In such a case, you can prevent default navigation from happening, take your time to generate the page, and transition upon success. This is described in the JQM docs on dynamically injected content. The advantage is that you can still rely on standard href links navigation, but it requires a bit more code and design upstream to properly detect and act upon navigation to the pages.

    $(document).on( "pagebeforechange", function( e, data ) {
        if ( typeof data.toPage === "string" ) {
             if ( data.toPage === "myDynamicPageName" ) {
                 e.preventDefault(); //used to stop transition to the page (for now)
    
                 /*
                    Here you can make your ajax call
                    In you callback, once you have generated the page you can call
                    $.mobile.changePage
                    (you can pass the Div of the new page instead of its name as
                    the changepage parameter to avoid interrupting again the page change) 
                 */
              }
          }
    });