0

In order to execute all commands once the page has been loaded, I am maintaing an array which pushes all the commands. This is being done via:

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

This is an iterative process and is run in a loop approximately 20 times.

I want that once this has been completed (page is completely loaded) and all the onload() events have been stacked into the array, execute each one by one.

I thought that $(document).ready() would let me achieve this, but it isn't helping either. However, using a setTimeout() function lets be see the ultimate result. But that obviously is not a good thing to do.

getPoster function:

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

How do you think I should go about to load the images once all the onload events are stacked?

4

4 回答 4

1

只需跟踪调用了多少次getPoster(),一旦调用计数达到执行每个命令的图像总数。

于 2013-04-22T16:23:54.190 回答
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');

看看这里,jQuery APItrigger()

于 2013-04-22T16:24:56.123 回答
0

您可以通过使用 ImagesLoaded 插件来实现:

https://github.com/desandro/imagesloaded

于 2013-04-22T16:23:02.077 回答
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();
    });

});
于 2013-04-22T16:28:58.350 回答