Skip to content

Instantly share code, notes, and snippets.

@schmidtsonian
Created April 12, 2019 20:47
Show Gist options
  • Save schmidtsonian/b6b12e0d5b17ffce1ea1e92e878b7984 to your computer and use it in GitHub Desktop.
Save schmidtsonian/b6b12e0d5b17ffce1ea1e92e878b7984 to your computer and use it in GitHub Desktop.
Creates and loads a single image
/**
* Creates and loads a single image
* @param {Object} attrs - Image element attributes
* @returns {Promise} {elm: img}
* @example
* loadImage({ src: 'foo.jpg', alt: 'foo' })
* .then(obj => console.log(obj.elem));
*/
export function loadImage(attrs) {
const p = new Promise( (resolve, reject) => {
const img = document.createElement('img');
// Resolve on load
img.addEventListener('load', () => resolve({elem: img}));
// Reject on error
img.addEventListener('error', () => reject({elem: img, error: true}));
// Set passed attrs
for (const attr in attrs) {
if (attr) {
img.setAttribute(attr, attrs[attr]);
}
}
});
return p;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment