I'm trying to load an image in JavaScript:
loadImage(src, img) {
return new Promise((resolve, reject) => {
img.onload = resolve;
img.onerror = reject;
img.src = src;
});
}
The img
has been created before, but doesn't exist in the DOM yet. It should be appended once it has loaded.
My problem: As far as I understand, it's not actually going to load the image, because the element is not part of the DOM yet.
I tried to use new Image()
, because this will load the image source before being inserted into the DOM:
loadImage(src, img) {
return new Promise((resolve, reject) => {
var tmp = new Image();
tmp.onload = resolve;
tmp.onerror = reject;
tmp.src = src;
img.src = src;
});
}
However, this did the loading twice and felt buggy.
I need to keep (and use) the img
element, as other event handlers and attributes are attached to it.
What can I do to load the image and resolve the promise once it's done?