ajax完成后的jQuery .load()函数。在100%加载之前不要显示图像

时间:2012-01-15 23:19:34

标签: jquery ajax history.js

我正在使用此处找到的ajaxify-html5.js脚本:https://github.com/browserstate/ajaxify

该脚本运行良好,除了当内容加载时(第145行:$content.html(contentHtml).ajaxify();),您仍然可以看到加载的图像。我想创建一个删除“加载”类(通过CSS转换淡入和淡出内容)的函数,但只有ajax内容不仅仅被提取,而是完全加载,以避免显示部分加载的图像。 / p>

我已经尝试在第146行插入以下内容但它没有被执行。

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

有什么想法吗?

谢谢!


更新:基于卡里姆回答的最终工作代码:

$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");   
    }
});

1 个答案:

答案 0 :(得分:3)

我不确定这是如何适用于该插件的,但我在这种情况下使用的一般解决方案(我已根据我的能力调整它以适应您的情况)如下:

$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");   
        }
    });
});