jQuery 1.5 introduced the Deferred Object to register callbacks for asynchronous events. Although the jQuery documentation contains examples on how to use Deferred objects for image loading, jQuery does not provide a simple interface for this common task.
This plugin provides a single function, jQuery.image()
, which acts
as a wrapper for the native image element constructor, and
creates a Deferred object that will be resolved when an image has
loaded.
Most easily, the plugin can be installed via Bower:
bower install jquery-image
To build and install from source, you need to have npm and grunt installed. In the repository's root directory, run:
npm install
grunt test
grunt dist
Either way, uncompressed and minified JavaScript files for inclusion
in your project will be available in the dist
directory:
dist/jquery.image.js
dist/jquery.image.min.js
Create a new Image element with optional parameters width
and
height
, and a corresponding Deferred object that will be resolved
when the image has finished loading from src
, or rejected if an
error occurs. The function returns the Promise from the Deferred
object. The image will be passed to the doneCallbacks and
failCallbacks as their sole argument.
Insert an image into the DOM after it has finished loading:
$.image( "images/example.jpg" ).done(function( img ) {
$( "#images" ).append( img );
});
Insert a scaled image into the DOM after it has finished loading, or alert the user if an error occurs:
$.image( "images/example.jpg", 80, 80 ).then(
function( img ) {
$( "#images" ).append( img );
},
function( img ) {
alert( "Cannot load image " + img.src );
}
);
Preload multiple images:
var img1 = $.image( "images/example1.jpg" );
var img2 = $.image( "images/example2.jpg" );
var img3 = $.image( "images/example3.jpg" );
$.when( img1, img2, img3 ).done(function( img1, img2, img3 ) {
$( "#images" ).append( img1 ).append( img2 ).append( img3 );
});
Copyright 2014 Thomas Kemmer.
Licensed under the MIT License.