用jquery的deferred对象实现判断页面中所有图片加载完成

17494次浏览

判断页面中所有图片是否加载完成

对于图片是否加载完成,我们平时可以用监听图片load 方法来进行。今天主要介绍用jquery的deferred对象来进行判断。

关于jquery的deferred对象,是jquery的重点和难点。对于执行较长时间的函数,我们通常用deferred对象。关于jquery的deferred对象的API请看http://api.jquery.com/category/deferred-object/ 对于deferred对象,大家可以看下阮一峰写的一篇文章jQuery的deferred对象详解

关于deferred对象,我在这里稍微介绍一下$.when().then()

function successFunc(){ console.log( “success!” ); } 
function failureFunc(){ console.log( “failure!” ); } 

$.when( 
$.ajax( "/main.php" ), 
$.ajax( "/modules.php" ), 
$.ajax( “/lists.php” ) 
).then( successFunc, failureFunc ); 

可以同时调用多个ajax,然后通过then来返回成功或者失败。

或者

$.when($.ajax("test1.html"), $.ajax("test2.html"))
.done(function(){ alert("哈哈,成功了!"); })
.fail(function(){ alert("出错啦!"); });

我们回到正题来,用jquery的deferred对象实现判断页面中所有图片加载完成

var defereds = []; //定义一个数组存放Deferred对象

$imgs.each(function() { //imgs循环所有图片
    var dfd = $.Deferred();// 新建一个deferred对象

    $(this).load(dfd.resolve());// 图片加载完成之后,改变deferred对象的执行状态
    defereds.push(dfd);//push到数组中
});
$.when.apply(null, defereds).done(function() {
    console.log('load compeleted');
});

因为 $.when 支持的参数是 $.when(dfd1, dfd2, dfd3, ...),所以我们这里使用了 apply 来接受数组参数。

上面提到了apply(),又引申到了 在JS中,call()方法和apply()方法

我在这里稍微介绍一下apply()

假如我们有prints函数:

function prints(a,b,c,d){
        console.log(a+b+c+d);
    }
   function example(a,b,c,d){
       prints.apply(this,[a,b,c,d]);
   }
   example("1","sd","wq","wqe") //输出:1sdwqwqe

或者我们可以这么写:

prints.apply(null,["前","端","博","客"]);//输出:前端博客

插件实现判断是否页面中图片加载完成

javascript有个imagesLoaded插件,可以用它判断页面图片是否加载完成,

插件地址:https://imagesloaded.desandro.com/

Tags: jquery图片deferred

相关文章:

  1. lee
    1
    赞👍👍👍👍👍👍👍👍👍👍👍👍