Calling a function when the background image finishes loading
I am loading a remote file 开发者_JAVA百科as a background image, and it could take up to 2 seconds, depending on the internet connection.
I would like to trigger a function when the background image completes loading.
It would work something like this (although this obviously does not)
$("body").css("background image","url('very_big_remote_image')", function(data){alert("done")} );
Try this, basically I load an image object and set its source to the background. Once it has loaded I change the background and fire the callback:
var img = new Image();
img.onload = function() {
$("body").addClass("bg");
//the callback function call here
};
img.src = 'very_big_remote_image';
This image is never shown, just forces browser to load it then it is cached.
Then have this in your css:
body.bg {
/* change the position or repeat or whatever else you need in this line */
background: url('/path/to/the/image/above.jpg') no-repeat 0 0 transparent;
}
jQuery has a load event function with a callback mechanism:
$("<img />").attr('src', 'img/pic.png').load(function() { /* Do stuff */ });
There are a number of variations.
http://jquery-howto.blogspot.com/2009/02/preload-images-with-jquery.html
http://api.jquery.com/load-event/
精彩评论