Created
April 12, 2019 20:47
-
-
Save schmidtsonian/b6b12e0d5b17ffce1ea1e92e878b7984 to your computer and use it in GitHub Desktop.
Creates and loads a single image
This file contains hidden or 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
/** | |
* 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