Reputation: 1125
I got this jQuery pre-loading script running on a index.html page loading about 10Mb before redirecting to a other page.
It works fine in IE8/9 FF3+ and Chrome. But it does not seem to work in IE6/7, it seems to start and run but never fires the last part.
Working example: -removed-
Anyone knows why it gets stuck on 75/76 files loaded in ie6/7?
<script src="js/jquery-1.7.1.min.js"></script>
<script>
(function($) {
var imgList = [];
$.extend({
preload: function(imgArr, option) {
var setting = $.extend({
init: function(loaded, total) {},
loaded: function(img, loaded, total) {},
loaded_all: function(loaded, total) {}
}, option);
var total = imgArr.length;
var loaded = 0;
setting.init(0, total);
for (i = 0; i < imgArr.length; i++) {
imgList.push($("<img />")
.load(function() {
loaded++;
setting.loaded(this, loaded, total);
if(loaded == total) {
setting.loaded_all(loaded, total);
}
})
.attr("src", imgArr[i])
);
}
}
});
})(jQuery);
$(function() {
$.preload([
"http://www.erikderuiter.nl/images/300x300-transparent.png",
"http://www.erikderuiter.nl/images/300x300.png",
"http://www.erikderuiter.nl/images/300x600.png",
"http://www.erikderuiter.nl/images/600x300.png",
"http://www.erikderuiter.nl/images/600x600.png",
"http://www.erikderuiter.nl/images/900x300.png",
], {
init: function(loaded, total) {
$("#indicator").html("Files: "+loaded+"/"+total);
},
loaded: function(img, loaded, total) {
$("#indicator").html("Files: "+loaded+"/"+total);
$("#full-screen").append(img);
},
loaded_all: function(loaded, total) {
$("#indicator").html("Loading: Done!");
window.location.replace("http://www.erikderuiter.nl/somepage.html");
}
});
});
</script>
<div id="indicator"></div>
Any other tips or best practices to preload images on a page are welcome as well of course.
Upvotes: 1
Views: 430
Reputation: 95022
You need to also test if the image is already cached.
var img = new Image();
img.src = "foo.jpg";
if (img.complete || img.readyState === 4) {
// image is cached
}
else {
$(img).bind("load error onreadystatechange",function(e){
// image is loaded
});
}
If there is a 404 error on one of the images, you will need to catch that with a setTimeout
and clearTimeout
.
Edit: Just a note before i get bombarded for using .bind
: I still use .bind
in plugins for backwards compatibility.
Here's an example of the above method: https://github.com/tentonaxe/jQuery-preloadImages/blob/master/jquery.preloadimages.js
Edit again: After reading this over again, I'm not sure if caching is the problem you are having at the moment. It's definitely something that may come up later if you don't check for it, but it may not be related to the problem you are having.
Upvotes: 1