Creating an image randomly fails in IE only
When I create an image in jQuery, set i's attributs with .attr() and then wait for it to load with .load() before animating the script randomly stops in IE. It always fails before the .load().
Any help would be very much appreciated. Even a different way of doing things would be helpful.
Thanks.
$('<img />')
.attr({
src: new_src,
width: '820',
height: '575',
alt: '',
'class': 'bg_image'
})
.load(function(){
//append image to #main2
$('#main2').append( $(this) );
//animate backgrounds
$("#main2").animate({left: $main_left + "px"开发者_StackOverflow}, 'slow');
$("#main").animate({left: new_left + "px"}, 'slow', function() {
if($rand){
document.location = $href + '?i=' + $rand;
} else {
document.location = $href;
}
});
});
There are two thing you need to do:
- set the
src
after theonload
handler to ensure that theevent
is not fired before you could attach the handler - set a handler to
error
event for the link might be broken and you have to handle that
Code
$('<img />').attr({
width: '820',
height: '575',
alt: '',
'class': 'bg_image'
}).load(function () {
//append image to #main2
$('#main2').append(this);
//animate backgrounds
$("#main2").animate({
left: $main_left + "px"
}, 'slow');
$("#main").animate({
left: new_left + "px"
}, 'slow', function () {
document.location = $href;
document.location += $rand ? '?i=' + $rand : '';
});
}).error(function(){
// simply redirect on error
document.location = $href;
document.location += $rand ? '?i=' + $rand : ''
}).attr("src", new_src); // set the src last
You need some slight adjustment, like this:
$('<img />').attr({
src: new_src,
width: '820',
height: '575',
alt: '',
'class': 'bg_image'
}).one('load', function(){
//append image to #main2
$('#main2').append(this);
//animate backgrounds
$("#main2").animate({left: $main_left + "px"}, 'slow');
$("#main").animate({left: new_left + "px"}, 'slow', function() {
document.location = $rand ? $href + '?i=' + $rand : $href;
});
}).each(function() {
if(this.complete) $(this).load();
});
The key here is that the load
event doesn't fire in some browsers if it was loaded from cache, because the load
happened when the src
was set, instantly, before you bound the .load()
handler.
To handle this, we're using .one()
to ensure the load
handler only runs once, then after creating the images, we're looping through and if they're .complete
(loaded from cache immediately most likely) we're calling .load()
to make sure that event handler runs.
精彩评论