PDA

View Full Version : Image Preloader


joh6nn
01-09-2005, 06:56 AM
someone had been asking about getting images to load in a specific order a while back, and while i was thinking about that, i came up with the following preloader script. the thing that separates this one from most of the other ones you'll find is that it lets you know if any of the images didn't load. if i weren't too lazy (i'm actually posting 'cause i'm hoping someone will do this for me), i'd connect the XmlHTTP request object to the array of failed image urls, and get the actual error headers, too. then, if i were really ambitious, i'd manually feed that info into an error reporting script, like this one (http://webmonkey.wired.com/webmonkey/reference/javascript_code_library/handle_errors/?tw=reference&category=development) that Webmonkey (http://www.webmonkey.com) demonstrates.

anyway, here it is. it takes an array of url strings to load, and returns an array of the ones that failed, for whatever reason.

function preLoad(args){
if (document.images){
var img = new Image();
var failed = [];
img.onerror = function(){
failed[failed.length] = this.src;
if(args.length > 0){ this.src = args.shift(); }
}
img.onload = function(){
if(args.length > 0){ this.src = args.shift(); }
}
img.src = args.shift();
}
else { var failed = args; }
return failed;
}

Kor
01-13-2005, 07:40 PM
Hm... I used to think that a true preloader is impossible in javascript, as there will be always a delay between the html page loading time in cache (altogether with the code itself) and the images called by the src attribute loading time.

Was I wrong?

joh6nn
01-13-2005, 08:02 PM
hmm. are you talking about exploiting the fact that, generally speaking, javascript would download before the html for images, because the javascript is in the head of the document, and the images are in the body? if that's what you mean, i agree that it wouldn't work (or i'd be really really surprised if it would). that gave me an interesting idea, though, of something like this:

<a href="randomPage.html" onclick="preLoad('[urlString1, urlString2, urlString3]'); someFunction('randomPage.html'); return false">click here!</a>

where urlString1 - 3 are images on randomPage.html, and someFunction waits till preLoad has finished, and then advances to randomPage.

that wasn't the use that i had intended for preLoad(), though. i had simply intended for it to be used, as most other "pre-loader" scripts are, to pre-load images used in rollovers and animations.