Load Image from javascript
<span>
<img id="my_image" src="#" />
</span>
<span class="spanloader">
<span>set Loading Image Image</span>
</span>
<input type="button" id="btnnext" value="Next" />
<script type="text/javascript">
$('#btnnext').click(function () {
$(".spanloader").hide();
$("#my_image").attr("src", "1.jpg");
});
</script>
Sorry guys.
You can't rely on the image load event to fire but you can kind of rely on it in some situations and fallback to a maximum load time allowed. In this case, 10 seconds. I wrote this and it lives on production code for when people want to link images on a form post.
function loadImg(options, callback) {
var seconds = 0,
maxSeconds = 10,
complete = false,
done = false;
if (options.maxSeconds) {
maxSeconds = options.maxSeconds;
}
function tryImage() {
if (done) { return; }
if (seconds >= maxSeconds) {
callback({ err: 'timeout' });
done = true;
return;
}
if (complete && img.complete) {
if (img.width && img.height) {
callback({ img: img });
done = true;
return;
}
callback({ err: '404' });
done = true;
return;
} else if (img.complete) {
complete = true;
}
seconds++;
callback.tryImage = setTimeout(tryImage, 1000);
}
var img = new Image();
img.onload = tryImage();
img.src = options.src;
tryImage();
}
use like so:
loadImage({ src : 'http://somewebsite.com/image.png', maxSeconds : 10 }, function(status) {
if(status.err) {
// handle error
return;
}
// you got the img within status.img
});
Try it on JSFiddle.net
http://jsfiddle.net/2Cgyg/6/
you can just append another hidden img
element and swap them in onload
event.
Or use single image element and use javascript like:
var _img = document.getElementById('id1');
var newImg = new Image;
newImg.onload = function() {
_img.src = this.src;
}
newImg.src = 'http://whatever';
this code should preload the image and show it when it's ready
Use a new image object each time you want to load a picture :
var image = new Image();
image.onload = function () {
document.getElementById('id1').setAttribute('src', this.src);
};
image.src = 'http://path/to/image';