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

标签 jquery ajax history.js

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

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

我尝试在第 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");   
    }
});

最佳答案

我不确定这将如何适合该插件,但我在这种情况下使用的通用解决方案(我已尽力调整它以适应您的情况)如下:

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

关于ajax 完成后的 jQuery .load() 函数。 100% 加载之前不显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8874263/

相关文章:

javascript - 如何使用 onclick 事件在同一窗口和选项卡中打开链接?

javascript - 使用history.js来检测是否支持HTML4,这样我就可以绕过ajax

javascript - AJAX 功能不能通过滚动工作

javascript - 根据浏览器的宽度调整 div 的宽度

jQuery-UI 自动完成功能不起作用

javascript - 带有参数的 Primefaces ajax 回调到 javascript

javascript - 尝试通过 AJAX 将 JS 数组传递给 PHP 脚本

javascript - IE9中的History.pushState添加Hash标签

javascript - 为什么我从 window.location 保存的变量发生变化?

c# - 允许用户编辑/添加/移动图像中的项目