preloading images


W

windandwaves

Hi Gurus

Preloading images has got to be JS 101. However, it does not seem to be
working. Here is the function that I am using. I added the alerts to make
sure it is working and all the right alerts show up, yet when I do my
mouseover, it still takes about a second (only the first time) to load the
image (thumbnail).

Am I missing anything?

loadims(max, letter) {//loads information images
if (document.images) {
max++;
alert(max);
for(i=1; i < max; i++) {
rslt = new Image();
imgn = 'm/' + letter + i + '.jpg';
rslt.src = imgn
alert(imgn);
}
loaded = true;
}
}


TIA

nicolaas
 
Ad

Advertisements

D

Daniel Kabs

Hello!
for(i=1; i < max; i++) {
rslt = new Image();
imgn = 'm/' + letter + i + '.jpg';
rslt.src = imgn

I think, instead of loading into a transient image object you should
rather preload the images into seperate and persistent image objects.

Did you try making rslt a global Array of Images?

Cheers
Daniel

PS: Giving an URL that links to an example on the net is always helpful.
 
Ad

Advertisements

I

Ivo

Preloading images has got to be JS 101. However, it does not seem to be
working. Here is the function that I am using. I added the alerts to
make sure it is working and all the right alerts show up, yet when I do my
mouseover, it still takes about a second (only the first time) to load the
image (thumbnail).

Am I missing anything?

loadims(max, letter) {//loads information images

Presumably the keyword "function" slipped off the clipboard here.
if (document.images) {

This mistake is classic. Testing for "document.images" when "window.Image"
is the feature you are going to use.
max++;
alert(max);
for(i=1; i < max; i++) {
rslt = new Image();
imgn = 'm/' + letter + i + '.jpg';
rslt.src = imgn
alert(imgn);
}
loaded = true;
}
}

The variable that holds the image to load, is re-assigned to another image
in the very iteration of the loop. This leaves very little time for the
image to actually load. Try using unique variables for each preloaded image
instead, that way they can all load alongside eachother. Comapre this
preloading function:

var pr = []; // global variable
function preload() {
if( window.Image ) {
var p = arguments, i = p.length;
while(i--) {
pr = new Image();
pr.src = p;
} } }

This would be called with the image URL's as arguments, as many as you like,
and all in one call to the function:

preload( 'example.gif', '/example.jpg', '../example.png' );

hth
ivo
http://4umi.com/web/javascript/
 

Top