执行onload后的加载功能

时间:2013-04-22 16:20:47

标签: javascript jquery

为了在页面加载后执行所有命令,我正在维护一个推送所有命令的数组。这是通过以下方式完成的:

<img src='holder.js/200x280/text:name' 
     alt='name' width='200px' 
     onload='getPoster(this, name)'>

这是一个迭代过程,循环运行大约20次。

我想要一旦完成(页面已完全加载)并且所有onload()事件已堆叠到数组中,逐个执行

我认为$(document).ready()会让我实现这一点,但它也没有帮助。但是,使用setTimeout()函数可以看到最终结果。但这显然不是一件好事。

getPoster功能:

function getPoster(img, title) {
    commands.push(new titles(img, title));
}

一旦所有onload事件堆叠起来,您认为我应该如何加载图像?

4 个答案:

答案 0 :(得分:1)

一旦呼叫计数达到执行每个命令的图像总数,就可以跟踪调用getPoster()的次数。

答案 1 :(得分:0)

您可以使用ImagesLoaded插件实现:

https://github.com/desandro/imagesloaded

答案 2 :(得分:0)

JavaScript是一种单线程同步语言。因此,基本上按照您编写的顺序处理指令。 Ajax请求是异步的,但加载像图像这样的东西不是。

因此,假设您必须调用4个函数onload,然后才能加载图像。这很容易,特别是如果你有jQuery。如果您没有发出Ajax请求或任何其他异步操作,则这些函数将同步执行,或者一个接一个地执行。

$(function() {//is equivalent to $(document).ready(function(){
    functionOne();
    functionTwo();
    functionThree();
    //etc
    loadImages();

});

为了达到你想要的效果,我能想到的最有效的方法是自定义event。使用类似的东西:

$('#foo').on('completedEveryThingElse', function(event) {
  // So bind the event to whatever wrapper and then trigger it when you are done
  // loading all other stuff.
  // Now start loading images.
});

// Whenever you are done loading everything else.
$('#foo').trigger('completedEveryThingElse');

查看HEREtrigger()

的jQuery API

答案 3 :(得分:0)

您可以使用:

<img class="posterImg" src='holder.js/200x280/text:name' alt='name' width='200px'>

$(document).ready(function () {    
    $(".posterImg").one('load', function () {
        getPoster(this,$(this).attr('alt'));
    }).each(function () {
        if (this.complete) $(this).load();
    });

});
相关问题