Show Page Loading Spinner on Ajax Call in jQuery Mobile
You can use the beforeSend
and complete
events of $.ajax
to call $.mobile.showPageLoadingMsg
and $.mobile.hidePageLoadingMsg
. Would look like this:
$('#main').live('pagecreate', function(event) {
$.ajax({
beforeSend: function() { $.mobile.showPageLoadingMsg(); }, //Show spinner
complete: function() { $.mobile.hidePageLoadingMsg() }, //Hide spinner
url: //url
dataType: 'json',
headers: //headers
success: function(data) {
//...
}
});
});
Before JQM 1.2:
$(document).ajaxStart(function() {
$.mobile.showPageLoadingMsg();
});
$(document).ajaxStop(function() {
$.mobile.hidePageLoadingMsg();
});
Since JQM 1.2:
$(document).ajaxStart(function() {
$.mobile.loading('show');
});
$(document).ajaxStop(function() {
$.mobile.loading('hide');
});
http://api.jquerymobile.com/page-loading/
A few people have asked about the workaround I ended up implementing, so I figured I'd share it. It's nothing particularly elegant or complicated, but it did seem to work. I haven't used the framework since the official 1.0 was released, so this may have been solved in the update. Essentially, I put the $.mobile.showPageLoadingMsg()
call into the pageshow
function, but wrapped it in an if clause that only fires the first time the page is shown:
var mainloaded = false;
$('#main').live('pageshow', function(event) { //Workaround to show page loading on initial page load
if(!mainloaded) {
$.mobile.showPageLoadingMsg();
}
});
$('#main').live('pagecreate', function(event) {
$.ajax({
url: //url
dataType: //datatype,
headers: //headers
success: function(data) {
//
//...loading stuff
//
$.mobile.hidePageLoadingMsg();
mainloaded = true;
}
//
//...handle error, etc.
//
});
});
This is a bit late...but you need to:
- Call
$.mobile.showPageLoadingMsg()
before the AJAX call. - Make the AJAX call. The call needs to be sent asynchronously (put
async: true
in your call). - Add
$.mobile.hidePageLoadingMsg()
in yoursuccess()
function.