Skip to content

Instantly share code, notes, and snippets.

@snorpey
Created April 23, 2014 08:06
Show Gist options
  • Save snorpey/11206425 to your computer and use it in GitHub Desktop.
Save snorpey/11206425 to your computer and use it in GitHub Desktop.
AMD module that loads an image. Caches images.
/*global define*/
/*
AMD module that loads an image. Caches images.
Note: this code has not been tested extensively. Use with caution.
MIT License
*/
define(
function ()
{
var images = { };
function loadImage ( image_url, callback )
{
if ( typeof callback === 'function' )
{
image_url = image_url.replace( /"/gi, '' );
if ( images[image_url] )
{
callback( images[image_url], image_url );
}
else
{
var image = new Image();
image.addEventListener( 'load', function () { imageLoaded( image, image_url, callback ); } );
image.src = image_url;
}
}
}
function imageLoaded ( image, image_url, callback )
{
images[image_url] = image;
callback( image, image_url );
}
return loadImage;
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment