How can jQuery mobile display a loader for a custom loading sequence?

I am currently working on a website application that contains a variety of images and interactive features. It is important to me that the page is only displayed once all images have loaded completely:

$(document).on('pageinit', function(){
    $('.ui-content').hide();
    var imgs = $(".ui-content img").not(function() { return this.complete; });
    var count = imgs.length;
    if (count) {
        imgs.load(function() {
            count--;
            if (!count) {
                $(".ui-content").show()
            }
        });
    } else {
        $(".ui-content").show();
    }
});

I am faced with the decision of either removing the loader entirely and replacing it with my own, or keeping the loader visible until the above function is completed.

How can I successfully remove the loader or ensure it remains visible until it is no longer necessary?

Answer №1

Creating a custom loader with jQuery Mobile

Solution Found:

To implement a custom loader with jQuery Mobile, you can refer to this working jsFiddle: http://jsfiddle.net/Gajotres/vdgB5/

The key is to initialize the Mobileinit event before jQuery Mobile is loaded and after jQuery is loaded. Additionally, some CSS changes need to be made for the custom loader to function properly.

Firstly, override the default ui-loader-default class by adjusting the opacity value to improve visibility of the spinner:

.ui-loader-default {
    opacity: 1 !important;      
}

Next, define the custom spinner style:

.custom-spinner {
    width: 37px !important;
    height: 37px !important;
    background-image:url('http://pictures.reuters.com/ClientFiles/RTR/Images/ajax-loader.gif');
    display: block;
}

Here is an example demonstrating how to implement the custom loader:

HTML code snippet:

<!DOCTYPE html>
<html>
    <head>
        <title>jQM Complex Demo</title>
        <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=no; target-densityDpi=device-dpi"/>
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
        <style>

            .ui-loader-default {
                opacity: 1 !important;      
            }

            .custom-spinner {
                width: 37px !important;
                height: 37px !important;
                background-image:url('http://pictures.reuters.com/ClientFiles/RTR/Images/ajax-loader.gif');
                opacity: 1 !important;
                display: block;
            }
        </style>
        <script type="text/javascript" src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js"></script>
        <script>
            $( document ).bind( 'mobileinit', function(){
                $.mobile.loader.prototype.options.text = "loading";
                $.mobile.loader.prototype.options.textVisible = false;
                $.mobile.loader.prototype.options.theme = "a";
                $.mobile.loader.prototype.options.html = "<i class='custom-spinner'></i>";
            }); 
        </script>       
        <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>    
        <script>
            $(document).on('pageshow', '#index', function(){        
                $.mobile.loading( 'show');          
            }); 
        </script>
    </head>
    <body>
        <div data-role="page" id="index">
            <div data-theme="a" data-role="header">
                <h3>
                    First Page
                </h3>
                <a href="#second" class="ui-btn-right">Next</a>
            </div>

            <div data-role="content">

            </div>

            <div data-theme="a" data-role="footer" data-position="fixed">

            </div>
        </div> 
    </body>
</html>   

Advanced Usage: Programmatic Control of jQuery Mobile AJAX Loader

Some browsers have the ability to programmatically control the jQuery mobile AJAX loader. For instance, WebKit browsers like Chrome allow manual execution using setInterval as shown below:

$(document).on('pagebeforecreate', '#index', function(){     
    var interval = setInterval(function(){
        $.mobile.loading('show');
        clearInterval(interval);
    },1);    
});

$(document).on('pageshow', '#index', function(){  
    var interval = setInterval(function(){
        $.mobile.loading('hide');
        clearInterval(interval);
    },1);      
});

Answer №2

Uncertain about the purpose behind your actions. The documentation provides several options for utilizing the loader:

Several individuals have mentioned that you can show/hide the loader by manually triggering it.

$.mobile.loading("show");

$.mobile.loading("hide");

Answer №3

One strategy I've employed during bootstrapping involves creating a loading screen as the initial data-role="page" div. Once the bootstrapping process is complete, I use the changePage function to transition programmatically to the home page, like so:

$.mobile.changePage( "#home", { reverse: false, changeHash: false } );

If you'd like to see an example, check out this fiddle:
http://jsfiddle.net/example123/Ghj6N/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensure the main checkbox is selected using jQuery

Currently, I am in the process of developing a JavaScript function that will automatically mark a parent checkbox if its child checkbox is checked (only if it's not already marked). For this task, I'm utilizing jQuery. Below is a snippet of my HT ...

From jQuery to Vanilla JavaScript: Implementing a simple click event listener

I've been attempting to translate the following jQuery code into vanilla JavaScript, however, I can't get it to function properly. jQuery: $(document).ready(function() { $("button").click(function() { var char = "0123456789abcdefghijklmno ...

Leveraging CamanJS for canvas filtering

These are my HTML elements: <div class="wrapper"> <nav class="navbar navbar-transparent"> <div class="container-fluid"> <div class="navbar-header"> <span class="btn btn-white btn-file"> ...

Is there a way in Javascript to save the inner HTML of an element in a cache so that it can be re-rendered after the page is refreshed

Is there a way to cache part of a webpage on the client side using JavaScript/jQuery? Does this method have any limitations in terms of the amount of data that can be cached? How can I access this cache after refreshing the page in order to re-render it? ...

The display and concealment of a div will shift positions based on the sequence in which its associated buttons are clicked

I am in need of assistance with coding (I am still learning, so please excuse any syntax errors). What I am trying to achieve is having two buttons (button A and button B) that can toggle the visibility of their respective divs (div A and div B), which sh ...

Executing code after a delay using JQuery's setTimeout function

I am facing an issue while running a JQuery function that controls the start-up and shutdown of a server. The current code I have written is as follows - $(".stopServer").click(function(){ $.post("controller.php",{stop: 'true', server: this. ...

Can you explain the significance of an element's dimensions being declared as "auto x auto"?

Within my Angular application, Bootstrap is being utilized, resulting in the generation of some elements by the Bootstrap framework. Upon examination, I have observed that many of these elements possess dimensions labeled as auto x auto. This particular co ...

Modify the size of the text in an <iframe> using inline css

After attempting the command below, I noticed that the text size within the iframe remained unchanged. Is there a different method to adjust it? <iframe id="myiframe" src="**" height="230px" scrolling="no" style ...

What causes Safari to handle these table cells in such a distinct manner compared to Chrome and Firefox?

Exploring some basic HTML here. In Google Chrome (v57) and Firefox (v55), the two cells to the right have equal heights, while in Safari (v11) they do not. In Safari, the top cell adjusts to fit its content, leaving the remaining space for the bottom cell. ...

Set focus on Bootstrap modal when closing the popup near the input field within the body

Hello fellow members of the Stack Overflow community! I'm trying to make sure that when users click on a Bootstrap modal window, the input field automatically gets focused. I've attempted the code below but it's not working as expected. Any ...

Is your Ajax response suddenly failing to work after the initial attempt?

Describing my predicament: The code snippet below is what I have been using to insert a custom-designed div into my webpage. Initially, the div is successfully added; however, it stops working after the first instance. $('#addanother').click(fu ...

What is the best way to iterate through a JSON array of various cookies using a for...in loop to extract the key value pairs?

I could be approaching this in the wrong way, so I welcome any feedback and suggestions... My current approach involves saving panel states in a custom UI by utilizing cookies during the click function with the js-cookie (formerly jquery-cookie) plugin. T ...

Incorporating dynamic JavaScript animations with immersive 360-degree images

I've been exploring ways to replicate a solution similar to this one: Sample During my research, I came across some lightweight jQuery plugins that can enable 360 degree image rotation. However, there are still a few things I haven't figured out ...

The output from the xpath query is: [object Text]. Ideally, it should be a valid element

I am currently experiencing an issue with the text "Access my account" at the end of the page that has been causing errors <p class="breadcrumb"> <a href="http://www.examplewebsite/comm/index-eng.html" title="Titleblock">Home</a>& ...

Feeling overwhelmed by JavaScript jQuery errors when making an Ajax request?

I am facing an issue with two buttons on my webpage. One button triggers a table refresh using an ajax php request, while the other button is set to automatically refresh the table every 10 seconds. However, when attempting to access the document, I am enc ...

Issues with the functionality of the accordion menu

I have implemented an accordion menu on my website. However, I am facing an issue where the 2nd menu always slides up when it gets loaded instead of sliding up after clicking on it. I want the behavior to change so that the sub menus elaborate only upon cl ...

Restrict the number of rows in a real-time search JSON data by utilizing the $.each method

Is there a way to limit the number of rows returned in live search JSON data through URL? I attempted to count the table rows and return false, but it did not work. Any suggestions on how to achieve this? $(document).ready(function() { $.ajaxSetup ...

The Jquery Ui DatePicker is able to attach to a textbox, however it seems that after the initial use, all click events become

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://ww ...

Create an interactive table with dynamic content that prevents wrapping using the CSS property

I am trying to create a table with two columns and specific width. The left cell should display a single-line text with auto-ellipsis, while the right cell should have dynamic content that adjusts the width of the cell accordingly, shrinking the left cell& ...

method for restful web service

I am trying to send an Array as a parameter to a RESTful webservice using Jersey. There is a multiple select form on my website where users can choose multiple options. I then use AJAX to pass the selected values to the RESTful webservice. Here is the sel ...