Skip to content

Instantly share code, notes, and snippets.

@jonrandy
Created February 28, 2021 04:42
Show Gist options
  • Save jonrandy/dd81ebe8510d3706d465e653f90e332c to your computer and use it in GitHub Desktop.
Save jonrandy/dd81ebe8510d3706d465e653f90e332c to your computer and use it in GitHub Desktop.
Load Images in JS, do something when loaded
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