Callback for image loading with jQuery

While I was doing the demo for my previous post about “simulating image pan jQuery plugin” I’ve noticed that the first time that I was loading the script the actions were executed before even loading the image and resulting in failure. This days at my job I was doing a gallery plugin in jQuery and notice the same problem.

Sometimes you have to load dynamic images as a result of a AJAX request, and you want to be able to do things only after the image has finish loading. In this case the ready() function, which is a wrapper for the window.onload() function is not usefull, because it applies to the elements present at the beginning.

In this scenario you make a request and receive as a string a path for a new image you have to load. This is usefull if you have big images and want to wait until the images are loaded before doing anything else.

$(document).ready( function (){
function( data ){
//console.log(data); // ["test.jpg"]
var _image = new Image();
_image.src = data; = 'newImageId';
$(_image).load( function(){
//once image is loaded add it to the div and remove the preloading
$("#imageContainer").append( _image ).removeClass('loading');
// do other stuff
_image.alt = "test image";

I’ve tested it in IE, FF, Chrome and works with cache enabled/disabled. The secret, not a big one, is the usage of AJAX load() function which does a GET request in the background and allows a callback. The purpose of the load function is to inject some html code in the current page. If you want to change the src value for a current image and do a callback it will be a good idea to pass a random string to the GET request as your browser could cache the image name and content.

Demo here

About this entry