jQuery 等待 AJAX 页面完全加载

标签 jquery ajax image load

我使用AJAX在页面A上显示页面B的内容。

如何让 jQuery 在显示内容之前等待所有内容(文本、图像等)加载?

$.ajax({
    url:"pageB.html",
    beforeSend: function() {
        //show loading animation here
    }
    success: function(data) {
        //hide loading animation here
        $("body").append(data);
    }
});

在处理 AJAX 请求时,我使用 beforeSend 向用户显示加载动画。现在我想“延长”等待时间,以便加载动画不会消失,直到所有图像加载完毕。

我最初尝试隐藏附加数据,等待所有图像加载,然后显示内容 - $("body").on("load", "images class here", function() {//show content}) inside success 但事件没有似乎着火了。

有什么想法吗?

更新:

更新的代码:

$.ajax({
    url:"pageB.html",
    beforeSend: function() {
        //show loading animation here
    }
    success: function(data) {
        //hide loading animation here
        $("body").append(data);
        $("body").on("onload", "img", function() {//display content});
    }
});

最佳答案

您必须使用直接事件绑定(bind):

$("body img").on("load", function () { });
$("body .image-class").on("load", function () { });

而不是委托(delegate)绑定(bind):

$("body").on("load", "img", function() { });
$("body").on("load", ".image-class", function () { });

委托(delegate)绑定(bind)取决于事件冒泡,但并非每个事件都如此。看来"load"事件——至少来自 <img> -- 却没有。

示例:http://jsfiddle.net/DLy6j/

关于jQuery 等待 AJAX 页面完全加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10822619/

相关文章:

javascript - 在 PHP 中如何使用 $_REQUEST 检索输入数组以输入数据库

python - 在 Python PIL 中合并图像以生成动画 gif

javascript - 自定义选项更新 Magento 产品图像

javascript - 制作点击事件只影响父类的 child ?

jquery - jQ 检测具有特定 CSS 值的后代

javascript - 根据复选框输入在 html 中分屏

javascript - 单击时隐藏下拉菜单 - Bootstrap

javascript - 无法从 jQuery AJAX 请求获得响应

javascript - Jquery ajax 简单表单不起作用

image - 发票/OCR : Detect two important points in invoice image