'How to know when image preloading is done with javascript?
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?
Solution 1:[1]
Image elements have two events that you can subscribe to to know that the image has loaded: onload
and onerror
:
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.):
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);
});
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | slebetman |
Solution 2 |