cusejuice
cusejuice

Reputation: 10681

jQuery Mobile Wait Until Entire Page is Finished Loading

My question with jQuery Mobile is how to wait until a page is COMPLETELY loaded (all images, text) before actually loading it. To clarify, once the user clicks a link, the loading graphic stays on the screen while the page is loading, and once it's completely loaded, to hide the loading graphic and load the page.

Is this possible?

Upvotes: 1

Views: 1589

Answers (1)

Jasper
Jasper

Reputation: 76003

$(document).on('click', '.my-custom-links', function() {
    //get the requested page
    $.ajax({
        url     : this.href,
        success : function (page) {
            //get only the first data-role="page" element
            var $page = $(page).find('[data-role="page"]').first();

            //now bind an event handler to all the elements that will need to load
            var $assets       = $page.find('img, script, link'),
                assets_loaded = 0;

            //make sure to bind to the load event before adding the element to the DOM
            $assets.on('load', function () {
                assets_loaded++;
                if (assets_loaded == $assets.length) {
                    //all the assets have loaded, so navigate to the new page
                    $.mobile.changePage($page);
                }
            });

            //add new page to the DOM
            $.mobile.pageContainer.append($page)
        },
        error   : function (jqXHR, textStatus, errorThrown) { /*Don't forget to handle errors*/ }
    });
    return false;
});

There's a first-crack at it. The basic idea isn't too far off from what @Kevin B. commented. Hi-jack the clicks on certain links, grab the page the link targeted, add it to the DOM, and then only show it after the assets have loaded.

Upvotes: 2

Related Questions