A-A+

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

2016年01月13日 前端设计 暂无评论 阅读 7 views 次

jquery的deferred对象实现判断页面中所有图片加载完成在应用中到不多了,我们用到最多的是其它的方案了,不过今天发现deferred做起来非常的不错,下面来看看,判断页面中所有图片是否加载完成.

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

关于jquery的deferred对象,是jquery的重点和难点。对于执行较长时间的函数,我们通常用deferred对象。关于jquery的deferred对象的API请看http://api.jquery.com/category/deferred-object/ 对于deferred对象,大家可以看下阮一峰写的一篇文章jQuery的deferred对象详解,关于deferred对象,我在这里稍微介绍一下$.when().then(),代码如下:

  1. function successFunc(){ console.log( “success!” ); }   
  2. function failureFunc(){ console.log( “failure!” ); }  
  3. $.when(   
  4. $.ajax( "/main.php" ),   
  5. $.ajax( "/modules.php" ),   
  6. $.ajax( “/lists.php” )   
  7. ).then( successFunc, failureFunc );  

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

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

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

  1. var defereds = []; //定义一个数组存放Deferred对象  
  2. $imgs.each(function() { //imgs循环所有图片  
  3.     var dfd = $.Deferred();// 新建一个deferred对象  
  4.     $(this).load(dfd.resolve());// 图片加载完成之后,改变deferred对象的执行状态  
  5.     defereds.push(dfd);//push到数组中  
  6. });  
  7. $.when.apply(null, defereds).done(function() {  
  8.     console.log('load compeleted');  
  9. });  

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

上面提到了apply(),又引申到了 在JS中,call()方法和apply()方法,我在这里稍微介绍一下apply(),假如我们有prints函数,代码如下:

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

或者我们可以这么写:

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

标签:

给我留言