In this example, I can get the following code to create the dynamic image in div#add
element when I click the button, but the load event for the img
does not work.
<html>
<head>
<title>None!</title>
<script type="text/javascript" src="Scripts\jquery-1.6.2.min.js"></script>
</head>
<body>
<button id="click">Click</button>
<div id="add"></div>
<script>
$(document).ready(function(){
$('#click').click(function() {
$('div#add').append('<img src="./images/imagename.jpg" />');
});
$('img').bind('load',function(){
alert('test');
});
});
</script>
</body>
</html>
I have also tried setting the onload
event on the dynamic img
but I did not get the event to fire. Any help is much appreciated.
Update (2011-10-24 18:55 EST): It appears that JQuery documentation for Load-Event states the following.
Caveats of the load event when used with images
A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:
-It doesn't work consistently nor reliably cross-browser
-It doesn't fire correctly in WebKit if the image src is set to the same src as before
-It doesn't correctly bubble up the DOM tree
-Can cease to fire for images that already live in the browser's cache
I guess using the load event is not a fail safe, cross-browser solution.
Update (2011-10-28 15:05 EST): Thanks to @Alex, I was able to use his waitForImages plugin and make a listener (I'm not sure if that is the right term) to determine when an image has been loaded.
<html>
<head>
<title>None!</title>
<script type="text/javascript" src="Scripts\jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="Scripts\jquery.waitforimages.js"></script>
</head>
<body>
<button id="click">Click</button>
<div id="add"></div>
<script>
$(document).ready(function(){
setInterval(function(){
$('div#add img.art').waitForImages(function() {
$('div#add img.load').hide();
$(this).show();
});
}, 500);
$('#click').click(function() {
$('div#add').append('<img class="load" src="./images/loading.gif" /><img style="display:none;" width="199" class="art" src="./images/imagename.jpg" /><br />');
});
});
</script>
</body>
</html>
So right now there is a maximum of 500 ms lag in determining if an image has been loaded. Does this seem reasonable? Is this the best way to see if a dynamically created img tag has been loaded?
Outstanding: I have to stop the setInterval
function from triggering after all of the images have been loaded. I still have to work out the details on that.