Guide: Show loading message while moving between pages in jQueryMobile – Part 2

In part 1 , I discussed how to show loading message while moving between pages. The suggested approach works both for Single Page  Template and Multi Page template like a breeze. If you’re not expert in jQueryMobile, I recommend you go with it.

However, if you’re obsessed with clean optimized code, like myself. I assume that you’ve already selected to go with Single Page Template. If so, below an optimized version of the code, that show the loading message even before the initiation of  the target page

1: $(document).bind("pagebeforechange",function(e, data){
2:    var sPage = false;
3:    if (typeof data.toPage == 'object' 
          && data.toPage.attr('id') == 'index-page')
4:        showLoadingMessage(true);	
5:    if (typeof data.toPage =="string"){
6:        if (typeof $.mobile.activePage == 'object' 
          &&$.mobile.activePage.attr("data-url")) > -1)
7:	    sPage = true;
8:        if ( < 0 && !sPage)							
9:	    showLoadingMessage(true); 
10:   }

Let’s go over this line by line. Note that the conditions might be combined and optimized, however for illustration purposes I will keep them as above

  • Line 2: This is a variable that we will use if the user is trying to access the active page
  • Line 3:  for Single page template, as illustrated in part 1  is called twice, the first time data.topage is a string representing the URL of the page, and second after the page is retrieved and converted to a Page object.  Our purpose is to show the load message as early as possible, which means in the first call. However, there is one single exception to this. The index page, where the function is called once and the data.toPage is an object by then
  • Line4: seriously! You need explanation on this. It’s whatever you’ll do to show a loading message, I don’t care if you’re using  the built-in widget or building your custom loading message
  • Line 5:show the loading message on the first call of pagebeforechange
  • Lines 6 and 7: Here i want to check that the user is not trying to access the same page. This happens when you also close a popup, the pagebeforechange is triggered
  • Lines 8 and 9 : if  you’re  not trying to open a popup, access the same page  nor closing a popup, then show the loading message

That’s it folks! hope you found it interesting!

HINT: Make sure to include showLoadMsg:false in the options of any $.mobile.changePage

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: