怎么知道何时使用JavaScript进行图像预加载?
per 这个非常
function preloadImage(url) {
var img=new Image();
img.src=url;
}
受欢迎喜欢知道是怎么知道什么时候完成的?我只能做一个小的settimeout,假设它将在一些小延迟后完成,但是连接速度的变化,尤其是对于大图像或大量图像,这是不可靠的。
有什么方法可以确定何时完成加载?
Per this extremely popular question, preloading images with javascript is as easy as:
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.
Is there any way to actually know for sure when the loading is done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
图像元素有两个事件,您可以订阅以了解图像已加载:
onload
和onerror
:或者,如果您更喜欢承诺(因此您可以使用async/等待等等):
Image elements have two events that you can subscribe to to know that the image has loaded:
onload
andonerror
:Or if you prefer Promises (so you can use async/await etc.):
刚刚在 mdn文档图像类。有一个
完整的
布尔属性,可以告诉您是否完成了。Just found the answer to my own question on the MDN docs for the Image class. There is a
complete
boolean attribute that tells you whether it's done.