【问题标题】:Preloading Images not working预加载图像不起作用
【发布时间】:2012-12-28 05:38:21
【问题描述】:

我的脚本有问题。

我正在尝试将所有图像加载到一个数组中,然后检查它们是否都已加载,然后再继续。但它不起作用我同样没有收到任何错误,所以我不确定出了什么问题。

这就是我所拥有的:

window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       || 
          window.webkitRequestAnimationFrame || 
          window.mozRequestAnimationFrame    || 
          window.oRequestAnimationFrame      || 
          window.msRequestAnimationFrame     || 
          function( callback,  element){
            window.setTimeout(callback, 200 / 100);
          };
})();

function img_loader(){

for(var i in Images){
        Images[i]['img_src'].onload = function() {
            countImages ++;
        }
    }
}

function img_load_checker(){

    if(countImages == Images.length){
        return true;
    } else {
        requestAnimFrame( img_load_checker );   // keep checking
    }
}


window.countImages = 0;
img_loader();
    if(img_load_checker()){
            //this never gets executed - reason is unknown
    //continue with rest of the script
    }

这是console.log(Images);的结构

[1: Object, 2: Object]
1: Object
img_src: <img>
2: Object
img_src: <img>

谁能看出错误?

【问题讨论】:

  • 当你说“它不工作”时,具体是什么意思?
  • 你试过调试你的代码吗?控制台说了什么? JSLint 是怎么说的?
  • //continue with rest of the script 这部分脚本永远不会执行。

标签: javascript


【解决方案1】:

你的 if 语句永远不会像那样工作。

该函数调用不会神奇地坐在那里等待异步调用返回。

if(img_load_checker()){
        //this never gets executed - reason is unknown
//continue with rest of the script
}

使用回调!

for(var i in Images){
        Images[i]['img_src'].onload = function() {
            countImages ++;
            if (countImages == Images.length) {
                callSomeMethod();  <-- Call back
            }
        }
    }
}

function img_load_checker(){

    if(countImages == Images.length){
        callNextStep();
    } else {
        requestAnimFrame( img_load_checker );   // keep checking
    }
}
img_load_checker();

【讨论】:

  • 这是否意味着我不能只做return true
  • 是的,该功能正在异步触发。到它返回任何东西的时候,那个 if 语句已经在很久以前执行了。
  • 啊,我明白了 - 奇怪的是,虽然加载时从未发生过。我在加载功能中进行了警报测试 - 想知道它在存储为对象时是否不起作用。
  • 或者您将 onload 方式设置为延迟并且它永远不会触发,因为它已经触发了。
  • 有没有办法做到onload || is_already_loaded?满足任何一种情况?
【解决方案2】:

你不需要计时器:

Images[i]['img_src'].onload = function() {
    if(countImages++ >= Images.length)
    {
         loadingHasFinishedNowDoWhateverYouWant();
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-01
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    相关资源
    最近更新 更多