Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
confidence68 opened this issue Nov 19, 2015 · 0 comments

Comments

@confidence68
Copy link
Owner

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

对于图片是否加载完成,我们平时可以用监听图片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,["前","端","博","客"]);//输出:前端博客
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant