Loading images using fetch
and promises
If you use fetch to load images you may want to show them on the page or use them in other applications.
const loadImage = async (url) => {
return (
fetch(url)
// Extract as a blob
.then((resp) => resp.blob())
.then((blob) => {
return URL.createObjectURL(blob);
})
);
};
Then you can use the Object URL as you do any other URL.
<img src="placeholder.jpg" id="imageid" />
<script>
const img = document.querySelector("#imageid");
loadImage("myimage.jpg").then((url) => {
img.src = url;
});
</script>
If you want to use in other cases, you want a fully loaded img
element. You
probably should wait for the image to be loaded as it can take a period of time
to load up the image blob into memory.
const loadImage = (url) => {
return new Promise((resolve) => {
fetch(url)
// Extract as a blob
.then((resp) => resp.blob())
.then((blob) => {
// Image element to load the image into. Could be passed as a variable if you already have an element to load into.
const img = document.createElement("img");
// Use blob as object url
img.src = URL.createObjectURL(blob);
// wait for image to be loaded before resolving the promise
img.onload = () => {
resolve(img);
};
});
});
};