Tom Auger Tom Auger - 1 year ago 145
Javascript Question

substr() with negative value not working in IE

EDIT:I've changed the title, because the issue had nothing to do with IE image.load() firing - my substr() wasn't working (see accepted answer).

There's a ton of posts about making sure that you define your onload handler prior to assigning img.src in order to guarantee that the onload handler is in place in case the image is loaded from cache first.

This does not appear to the be issue in my code, since that's precisely what I have done.

Note that this script works across all other browsers, but IE 8 and lower does not trigger the onload inline function.

var i = lastSlideIndex || 1;

while(imagesQueued < MAX_IMAGES){
var preloadImage = new Image();
preloadImage.arrayIndex = i;
preloadImage.onload = function(eventObj){
debug('Image ' + this.src + ' loaded.');
slideshowImages[this.arrayIndex] = this;
if (this.arrayIndex > lastImageIndex) lastImageIndex = this.arrayIndex;

// add leading zeros
var leadingZeros = "0000000".substr(-(String(MAX_IMAGES).length));
imageNumber = leadingZeros.substr(String(i).length) + i;

debug('preloading Image #' + imageNumber);
preloadImage.src = fullImagePrefix + imageNumber + "." + IMAGES_TLA;

if (++i > MAX_IMAGES) i = 1;

Any other suggestions would be deeply appreciated!

Answer Source

Update: As commenters have pointed out (and I can't prove them otherwise for now), I removed the first suggestion.

Couple of more things to note:

onload event will not fire if the image is being loaded from cache. Try clearing your cache and retry.

Another problem is that IE doesn't like negative in substr. Use slice instead:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download