So I have a page with little picture thumbnails on it and one big area in the middle of the page for full size photo.
When user clicks on a thumbnail, a full size picture is shown in the middle of the page. I just change the src attribute of the image in the middle like this to achieve that:
$('img#fullsize').attr('src', path); // path is built earlier开发者_开发百科 in the jQuery code
The problem is that when the fullsize image is too large what it does is that the fullsize image in the middle disappears and nothing is there until the new full size image starts loading (and sometimes it can take cca 5 seconds until new image starts loading during peak hours). What I would like is to show an ajax loader gif image until the fullsize photo starts loading. How can I do that?
Thanks.
Don't know jQuery but <img>
has an onload
event. What you can do is
- set the
src
of the displayed image to the loading spinner gif, then - load the actual image into a hidden
img
, - once the
onload
event triggers swap thesrc
around:
code:
<!-- preload spinner gif: -->
<img src="loading_spinner.gif" style="display:none" />
<!-- img placeholders: -->
<img src="" id="fullsize" />
<img src="" id="hidden_img" style="display:none" />
<a href="javascript:loadFullSize()">Click here to load image</a>
<!-- load image: -->
<script>
function loadFullSize() {
function get (id) {return document.getElementsById(id)}
var visible = get('fullsize');
visible.src = 'loading_spinner.gif';
var hidden = get('hidden_img);
hidden.src = path;
hidden.onload = function(){
visible.src = path;
}
}
</script>
You can preload the spinner gif in case you are worried about that.
Without actual code just a short idea: What about defining a css background for your images? Should work except for transparent images (you'd have to remove the background later for these) - but actually: I have not tried this yet.
Loading images can be tricky. A reasonable cross-browser way to check if the image is loaded is to check for the complete param on the native Image object and width is greater than 0.
Something like this should work:
var img = $('img#fullsize').attr('src', path)[0];
window.setTimeout(function() {
if (img.complete && img.width) {
console.log('loaded!');
}
window.setTimeout(arguments.callee, 1);
}, 1);
onload fires before the image has actually loaded in firefox anyway....
edit: how embarassing, got it to work using onload and "proper" javascript. D'oh!
精彩评论