Image.onload 不执行所有代码



我有一段javascript,它正在拍摄多个图像并等待它们全部加载,然后对它们执行一些逻辑。这是一段剥离的代码,仍然没有达到预期:

$(window).on('load', function() {
    var art = new Image();
    var top_image = new Image();
    var bottom_image = new Image();
    var left_image = new Image();
    var right_image = new Image();
    art.onload = function() {
        console.log("1");
        top_image.onload = function() {
            console.log("2");
            bottom_image.onload = function() {
                console.log("3");
                right_image.onload = function() {
                    console.log("4");
                    left_image.onload = function() {
                        console.log("5");
                    }
                }
            }
        }
    }
    art.src = 'images/prototype.jpg';
    top_image.src = 'images/2_4_top_center.png';
    bottom_image.src = 'images/2_4_bottom_center.png';
    right_image.src = 'images/2_4_middle_right.png';
    left_image.src = 'images/2_4_middle_left.png';
});    

问题是,当我硬重新加载浏览器时,控制台中会出现一个看似随机的数字日志。它大多只记录"1",但有时一直记录"5"。我不确定这里发生了什么,以及为什么它有时只按预期运行。

您只需在

art已经加载时将onclick处理程序附加到top_image,因此如果top_imageart之前加载,则不会触发第二个处理程序。要解决此问题,请在设置其源之前将处理程序附加到所有图像,并使用 promise 来处理它们:

   const onload = img => new Promise(res => img.onload = res);
  var art = new Image();
  var top_image = new Image();
  var bottom_image = new Image();
  var left_image = new Image();
  var right_image = new Image();
  Promise.all([art, top_image, bottom_image, left_image, right_image].map(onload))
    .then(() => {
       // All loaded !!
    });
  // Add sources

最新更新