Skip to content

Instantly share code, notes, and snippets.

@lsmith
Created March 23, 2009 18:04
Show Gist options
  • Save lsmith/83692 to your computer and use it in GitHub Desktop.
Save lsmith/83692 to your computer and use it in GitHub Desktop.
// Wrapper function to create an img tag and execute a callback when it loads or
// the server returns an error (onload/onerror). Also handles img nodes currently
// on the page, and executes the appropriate handler according to the image's state.
// Mainly useful for insurance in knowing that the dimensions are available at a
// certain point in the processing.
// First a couple helper functions
function $(id) {
return !id || id.nodeType === 1 ? id : document.getElementById(id);
}
function isType(o,t) {
return (typeof o).indexOf(t.charAt(0).toLowerCase()) === 0;
}
// Here's the important part
/**
* Executes a success or failure callback in response to an image's loaded state.
* Creates the img element if not found.
*
* The configuration object supports the following keys:
* <dl>
* <dt>src</dt> <dd>Desired src of the img</dd>
* <dt>alt</dt> <dd>Desired alt attributes of the img</dd>
* <dt>target</dt> <dd>Desired parent element of the img</dd>
* <dt>insertBefore</dt> <dd>Node or id of the element inside the target to insert
* the img before (otherwise appended)</dd>
* <dt>success</dt> <dd>Function callback executed when the img is loaded. Immediately
* executed if the img is already loaded.</dd>
* <dt>failure</dt> <dd>Function callback executed if the server replies with an error.
* Immediately executed if already failed loading.</dd>
* </dl>
*
* The callbacks are executed from the scope of the img element
*
* @method image
* @param src {HTMLElement|Id|String} An img element, its id, or a src url to create
* a new img element.
* @param cfg {Object} Configuration object.
* @return {HTMLElement} the img element DOM node
function image(src,cfg) {
var img, prop, target;
cfg = cfg || (isType(src,'o') ? src : {});
img = $(src);
if (img) {
src = cfg.src || img.src;
} else {
img = document.createElement('img');
src = src || cfg.src;
}
if (!src) {
return null;
}
prop = isType(img.naturalWidth,'u') ? 'width' : 'naturalWidth';
img.alt = cfg.alt || img.alt;
// Add the image and insert if requested (must be on DOM to load or
// pull from cache)
img.src = src;
target = $(cfg.target);
if (target) {
target.insertBefore(img, $(cfg.insertBefore) || null);
}
// Loaded?
if (img.complete) {
if (img[prop]) {
if (isType(cfg.success,'f')) {
cfg.success.call(img);
}
} else {
if (isType(cfg.failure,'f')) {
cfg.failure.call(img);
}
}
} else {
if (isType(cfg.success,'f')) {
img.onload = cfg.success;
}
if (isType(cfg.failure,'f')) {
img.onerror = cfg.failure;
}
}
return img;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment