【问题标题】:How to use image onload in the loop?如何在循环中使用图像加载?
【发布时间】:2019-02-09 04:56:26
【问题描述】:
  1. 我想按顺序添加新的 Image()。
    例如,
荷兰_001.jpg, 荷兰_002.jpg, 荷兰_003.jpg, : :

当我不使用Onload 时,图像会按顺序附加。
但是当我使用Onload 时,图像并没有按顺序附加。

以下是 concole 日志,您可以在其中看到图像附加不按顺序。

/C:/Users/TSUBYAM/Desktop/Web/images/netherlands/netherlands_008.jpg:1 获取文件:///C:/Users/TSUBYAM/Desktop/Web/images/netherlands/netherlands_008.jpg net::ERR_FILE_NOT_FOUND 图片(异步)(匿名)@load_picture.js:19 load_picture.js:17 未找到:../images/netherlands/netherlands_008.jpg load_picture.js:13 找到:../images/netherlands/netherlands_006.jpg load_picture.js:13 找到:../images/netherlands/netherlands_001.jpg load_picture.js:13 找到:../images/netherlands/netherlands_003.jpg load_picture.js:13 找到:../images/netherlands/netherlands_005.jpg load_picture.js:13 找到:../images/netherlands/netherlands_004.jpg load_picture.js:13 找到:../images/netherlands/netherlands_002.jpg load_picture.js:13 找到:../images/netherlands/netherlands_007.jpg
  1. 我也想在找到不存在的图片路径时退出循环。
荷兰_001.jpg, 荷兰_002.jpg, 荷兰_003.jpg, etherlands_004.jpg, # 如果不存在,我想在这里退出循环。 etherlands_005.jpg, # 那我就不用加载这个图片了。 : :

我无法退出循环,因此我使用了“style.display = none”。所以我不显示不存在的图像。

这是我的代码。

    let file_name = window.location.href.split('/').pop();
    let country = file_name.split(/\./)[0];
    let parent_img = document.getElementsByClassName("pic")[0];

    for ( var i = 0; i < 8; i++)
    {
        // get file image
        let pic_num  = ("000" + (i + 1)).slice(-3);
        let pic_name = `${country}_${pic_num}.jpg`;
        let pic_path = "../images/" + country + "/" + pic_name;

        let newImage = new Image();

        newImage.onload = function(){
            console.log(`Found: ${pic_path}`);
        }
        newImage.onerror = function(){
            this.style.display = 'none';
            console.log(`Not Found: ${pic_path}`);
        }
        newImage.src = pic_path;
        newImage.alt = pic_name;
        parent_img.appendChild(newImage);
    }

【问题讨论】:

    标签: javascript onload


    【解决方案1】:

    如果将循环放入async函数中,则可以将await每个onload(或onerror)转换成Promise

    (async () => {
      const file_name = window.location.href.split('/').pop();
      const country = file_name.split(/\./)[0];
      const parent_img = document.querySelector(".pic");
    
      for (let i = 0; i < 8; i++) {
        // get file image
        const pic_num = ("000" + (i + 1)).slice(-3);
        const pic_name = `${country}_${pic_num}.jpg`;
        const pic_path = "../images/" + country + "/" + pic_name;
    
        const newImage = new Image();
        try {
          newImage.src = pic_path;
          newImage.alt = pic_name;
          await new Promise((resolve, reject) => {
            newImage.onload = function() {
              console.log(`Found: ${pic_path}`);
              resolve();
            }
            newImage.onerror = function() {
              console.log(`Not Found: ${pic_path}`);
              reject();
            }
          });
        } catch(e) {
          // reject was called, break out of the loop:
          break;
        }
        parent_img.appendChild(newImage);
      }
    })();
    

    另一种方法是使用Promise.all并行请求所有图片,大大加快了加载速度,但只有在全部成功后才追加:

    (async () => {
      const file_name = window.location.href.split('/').pop();
      const country = file_name.split(/\./)[0];
      const parent_img = document.querySelector(".pic");
      Promise.all(Array.from(
        { length: 8 },
        (_, i) => {
          const pic_num = ("000" + (i + 1)).slice(-3);
          const pic_name = `${country}_${pic_num}.jpg`;
          const pic_path = "../images/" + country + "/" + pic_name;
          const newImage = new Image();
          newImage.src = pic_path;
          newImage.alt = pic_name;
          return new Promise((resolve, reject) => {
            newImage.onload = function() {
              console.log(`Found: ${pic_path}`);
              resolve(newImage);
            }
            newImage.onerror = function() {
              console.log(`Not Found: ${pic_path}`);
              reject();
            }
          });
        }
      ))
      .then((images) => {
        images.forEach((image) => {
          parent_img.appendChild(image);
        });
      });
    })();
    

    【讨论】:

    • 谢谢。这正是我想要做的。我也意识到需要更多地研究异步。
    猜你喜欢
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多