Hide page contents whilst loading via AJAX until all images loaded

Useful if many large photos contained inside page being loaded via AJAX, so they won't be seen loading jerkily

HTML

<button id="page-load">Load</button>
<div id="page-container"></div>

JavaScript

$(document).ready(function () {

    var $container = $("#page-container"); //cache selector for performance

    $("#page-load").click(function () {

        //Indicate to user that page is loading...
        $container.html("<img src='https://github.com/jquery/jquery-mobile/raw/master/css/themes/default/images/ajax-loader.gif' alt='Loading' />");
        //OR... $container.text("Loading...");
        //OR SIMPLY... $container.hide();

        //fetch page into memory...
        //$.get("page1.htm", success, "html"); //if not on JSFIDDLE
        $.post("/echo/html/", simulate, success, "html"); //for JSFIDDLE only

        //when page html loaded into memory...
        function success(html) {
            var $fragment = $("<div>").append(html); //load into a surrogate jQuery selector and cache for performance
            var $images = $("img", $fragment); //find images and cache for performance
            var remaining = $images.length; //number of images to be loaded within html

            //REMOVE AFTER TESTING. This is block is to simulate fresh loading
            var antiCache = "?_=" + $.now(); //create a unique string, for demo purposes
            $images.each(function () { //one-off cycle through each image in memory
                this.src += antiCache; //REMOVE: prevent cache, for demo purposes
            });
            //END OF BLOCK TO REMOVE
            
            $images.one("load", function () { //single-shot event handler for each image
                if (!(--remaining)) loaded(); //fire "loaded" once all images loaded
            });

            //when all images loaded...
            function loaded() {
                $container.html(html);
                //OR... $container.show(); //if container was initially hidden
            }
        }
    });
});













//DUMMY HTML CONTENTS for JSFIDDLE AJAX simulator..............
var simulate = {delay: 500, html:'<img...