I'm using the ajaxify-html5.js script found here: https://github.com/browserstate/ajaxify

The script is working great, except that when the content is loaded in (around line 145: $content.html(contentHtml).ajaxify(); ) you can still see the images loading. I would like to create a function which removes the "loading" class (which fades in and out the content with a CSS transition) but only once the ajax content is not just fetched, but completely loaded, to avoid showing partially loaded images.

I've tried inserting the following on line 146 but it doesn't get executed.

$content.load(function(){
    alert('asds');
    $body.removeClass('loading');
});

Any ideas?

Thanks!


UPDATE: Final working code based on Karim's answer:

$content.html(contentHtml).ajaxify(); /* you could fade in here if you'd like */

var $imgs = $content.find("img");
var loadCounter = 0;
var nImages = $imgs.length;
$imgs.load(function () {
    loadCounter++;
    if(nImages === loadCounter) {
        $body.removeClass("loading");
    }

// trigger load event if images have
// been cached by the browser
}).each(function () {
    if(this.complete) {
        $(this).trigger("load");   
    }
});
有帮助吗?

解决方案

I am not certain how this would fit in to that plugin, but a general solution which I use in such situations (I have adapted it to fit your situation to the best of my ability) is as follows:

$content.one("load", function() {
    var $imgs = $(this).find("img");
    $imgs.hide();
    var loadCounter = 0;
    var nImages = $imgs.length;
    $imgs.load(function () {
        loadCounter++;
        if(nImages === loadCounter) {

            // all the images have loaded
            // reveal them, remove the loading indicator
            $body.removeClass("loading");
            $imgs.show(); 
        }

    // trigger load event if images have
    // been cached by the browser
    }).each(function () {
        if(this.complete) {
            $(this).trigger("load");   
        }
    });
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top