PDA

View Full Version : problem with binding functions to image load



Trillium
08 Mar 2010, 03:29 PM
Hi,
I'm trying to create a photo album that displays a throbber for every single image in the album, and then uses jQuery to insert the proper image when the image is loaded, but the .load() method doesn't seem to be working the way that I want it to.

the javascript is:


function prepImages() {
// grab each loadable image
$('.loadable-image').each(function(){
var img = $(this);
// store its source attribute
var img_src = img.attr('alt');
// pre-load the image
imgOb = new Image();
imgOb.src = img_src;
//when the image loads
imgOb.load(function () { //this here is the problem line...
//set the old src equal to the loaded img src
img.attr('src', imgOb.src);
}); //this is the closing of the problem line
});
}
$(document).ready(function(){
// begin the slideshow
$('.slideshow').cycle({
fx: 'fade',
speed: 1000,
timeout: 1000,
pause: 1
});
// start inserting the images
prepImages();
});

and the html is:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-5" />
<title>Test: Async image loading</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.cycle.all.min.js"></script>
<script type="text/javascript" src="js/async_loading_custom.js"></script>
<link rel="stylesheet" type="text/css" href="css/async_loading_custom.css" media="screen" />
</head>
<body>
<table>
<tr><td><div class="album1">
<h1>Album 1</h2>
<div class="slideshow">
<a href="photos/pic1.jpg" title="photos/thumb_pic1.jpg"><img class="loadable-image" src="photos/ajax-loader.gif" alt="photos/thumb_pic1.jpg" /></a>
<a href="photos/pic2.jpg" title="photos/thumb_pic2.jpg"><img class="loadable-image" src="photos/ajax-loader.gif" alt="photos/thumb_pic2.jpg" /></a>
<a href="photos/pic3.jpg" title="photos/thumb_pic3.jpg"><img class="loadable-image" src="photos/ajax-loader.gif" alt="photos/thumb_pic3.jpg" /></a>
</div>
</div></td></tr>
</table>
</body>
</html>

if I take the code:
img.attr('src', imgOb.src); out of the load method, and get rid of the load method, then the code works, but I don't think that it waits till the images are loaded. If I run the code without the lines:

imgOb.load(function () {
and it's closing:

});
then the throbbers are replaced by the proper images just as they should be, but I don't have any assurance that the pictures are being loaded before they are displayed. The whole point of this, is to let the images load, and then to insert them when they are. That is what I'm trying to achieve, if there is a better way to do this, please let me know. I am interested in making my picture-heavy pages faster, so I would like to know more about controlling image loading.

Thank you for your help!