jQuery Mobile provides a loader widget to display a loading animation (also known as spinner, ajax loader, etc…). jQuery automatically uses this dialog, when it comes to loading ajax content. This dialog is also usefull if you do some processing other than ajax content loading, to provide a visual feedback to the user.

To programmatically control he loading dialog, jQuery provides a Javascript API. For example, you can show the dialog by calling

$.mobile.loading('show');

or hide the dialog via

$.mobile.loading('hide');

However, what is missing in the documention, this control is not available at anytime during your program execution. As described in this stack overflow thread, the loader can only controlled directly during the showpage event processing.

To solve this issue and control the loader widget at anytime, you must execute it asynchronously. This can be achieved by putting it into a setTimeout() callback.

function showLoader() {
    window.setTimeout(function(){
        $.mobile.loading('show');
    }, 1);
};

function hideLoader() {
    window.setTimeout(function(){
        $.mobile.loading('hide');
    }, 1);
};

Note: Some people, as in the stack overflow discussion mentioned above, use a solution based Javascript’s setInterval() method. It did not work reliably in my experience, and the intend of setInterval() is to execute something periodically. In our case, we want to control the loader widget only once. So setTimout() better fits to out intention.

jQuery Mobile: Controlling loading animation at any time

Post navigation


Leave a Reply