Created
February 28, 2021 04:42
-
-
Save jonrandy/dd81ebe8510d3706d465e653f90e332c to your computer and use it in GitHub Desktop.
Load Images in JS, do something when loaded
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function loadImage(url) { | |
return new Promise((resolve, reject) => { | |
let img = new Image(); | |
img.addEventListener('load', e => resolve(img)); | |
img.addEventListener('error', () => { | |
reject(new Error(`Failed to load image's URL: ${url}`)); | |
}); | |
img.src = url; | |
}); | |
} | |
async function go() { | |
// load the image, and append it to the element id="image-holder" | |
img = await loadImage('http://thecatapi.com/api/images/get?format=src&type=jpg&size=small') | |
document.getElementById('image-holder').appendChild(img) | |
} | |
go() | |
/* loadImage('http://thecatapi.com/api/images/get?format=src&type=jpg&size=small') | |
.then(img => document.getElementById('image-holder').appendChild(img)) | |
.catch(error => console.error(error)); */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment