简体   繁体   English

如何知道何时使用 javascript 完成图像预加载?

[英]How to know when image preloading is done with javascript?

Per this extremely popular question , preloading images with javascript is as easy as:根据这个非常流行的问题,使用 javascript 预加载图像非常简单:

function preloadImage(url) {
  var img=new Image();
  img.src=url;
}

But what I'd like to know is how can you know when that's done?但我想知道的是你怎么知道什么时候完成? I could just do a small setTimeout and assume it will be done after some small delay, but with varying connection speeds and especially for large images or large numbers of images this is unreliable.我可以只做一个小的 setTimeout 并假设它会在一些小的延迟后完成,但是随着连接速度的变化,特别是对于大图像或大量图像,这是不可靠的。

Is there any way to actually know for sure when the loading is done?有什么方法可以确定加载完成的时间吗?

Image elements have two events that you can subscribe to to know that the image has loaded: onload and onerror :图像元素有两个事件,您可以订阅它们以知道图像已加载: onloadonerror

function preloadImage(url, doneCallback) {
  var img=new Image();
  img.src=url;

  img.onload = () => {
    doneCallback();
  }

  img.onerror = () => {
    doneCallback(new Error('Failed to load image ' + url));
  }
}

preloadImage(url, (err) => {
  if (err) {
    console.log(err.message);
  }
  else {
    console.log('Preloading DONE!');
    // do what you want after preloading here!
  }
}

Or if you prefer Promises (so you can use async/await etc.):或者,如果您更喜欢 Promises(因此您可以使用 async/await 等):

function preloadImage(url) {
  var img=new Image();
  img.src=url;

  return new Promise((done, fail) => {
    img.onload = () => {
      done();
    }

    img.onerror = () => {
      fail(new Error('Failed to load image ' + url));
    }
  });
}

async function main () {
    console.log('preloading image!');

    await preloadImage(url);

    console.log('done preloading image!');
}

main().catch((err) => {
  console.log(err.message);
});

Just found the answer to my own question on the MDN docs for the Image class.刚刚在 Image 类的 MDN 文档上找到了我自己的问题的答案。 There is a complete boolean attribute that tells you whether it's done.有一个complete的布尔属性告诉你它是否完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM